| 1 |
<?php |
| 2 |
namespace Enteraddons\AI; |
| 3 |
|
| 4 |
/** |
| 5 |
* Enteraddons ai |
| 6 |
* |
| 7 |
* @package Enteraddons |
| 8 |
* @author ThemeLooks |
| 9 |
* @copyright 2022 ThemeLooks |
| 10 |
* @license GPL-2.0-or-later |
| 11 |
* |
| 12 |
* |
| 13 |
*/ |
| 14 |
|
| 15 |
|
| 16 |
class AI_API { |
| 17 |
|
| 18 |
private $api_url = 'https://api.enteraddons.com/wp-json/enteraddons/ai/v1/'; |
| 19 |
private $api_key; |
| 20 |
private $timeout = 120; |
| 21 |
|
| 22 |
public function __construct() { |
| 23 |
$this->api_key = 'EAT809-TAE854-AEE956-YUT235'; |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* Send POST request |
| 28 |
*/ |
| 29 |
public function post( $endpoint = '', $body = [] ) { |
| 30 |
|
| 31 |
$url = trailingslashit( $this->api_url ) . ltrim($endpoint, '/'); |
| 32 |
|
| 33 |
$response = wp_remote_post( $url, [ |
| 34 |
'timeout' => $this->timeout, |
| 35 |
'httpversion' => '1.1', |
| 36 |
'sslverify' => false, // disable only in dev |
| 37 |
'headers' => [ |
| 38 |
'Content-Type' => 'application/json', |
| 39 |
'X-API-Key' => $this->api_key, |
| 40 |
], |
| 41 |
'body' => wp_json_encode( $body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ), |
| 42 |
'data_format' => 'body' |
| 43 |
]); |
| 44 |
|
| 45 |
// |
| 46 |
if ( is_wp_error( $response ) ) { |
| 47 |
return [ |
| 48 |
'success' => false, |
| 49 |
'message' => $response->get_error_message() |
| 50 |
]; |
| 51 |
} |
| 52 |
|
| 53 |
// |
| 54 |
$getResponse = $this->handle_response( $response ); |
| 55 |
|
| 56 |
if( empty( $getResponse['success'] ) && !empty( $getResponse['message'] ) ) { |
| 57 |
return [ |
| 58 |
'success' => false, |
| 59 |
'message' => $getResponse['message'] |
| 60 |
]; |
| 61 |
} |
| 62 |
|
| 63 |
return $getResponse; |
| 64 |
} |
| 65 |
|
| 66 |
/** |
| 67 |
* Handle API response |
| 68 |
*/ |
| 69 |
private function handle_response( $response ) { |
| 70 |
|
| 71 |
$body = wp_remote_retrieve_body( $response ); |
| 72 |
|
| 73 |
if ( json_last_error() !== JSON_ERROR_NONE ) { |
| 74 |
return [ |
| 75 |
'success' => false, |
| 76 |
'message' => 'Invalid JSON response', |
| 77 |
'raw' => $body |
| 78 |
]; |
| 79 |
} |
| 80 |
|
| 81 |
$decoded = json_decode( $body, true ); |
| 82 |
|
| 83 |
if( !empty( $decoded['code'] ) && $decoded['code'] == 'error_code' ) { |
| 84 |
|
| 85 |
return [ |
| 86 |
'success' => false, |
| 87 |
'message' => $decoded['message'] ?? '', |
| 88 |
]; |
| 89 |
|
| 90 |
} |
| 91 |
|
| 92 |
// |
| 93 |
if( !empty( $decoded['code'] ) && $decoded['code'] == 'internal_server_error' ) { |
| 94 |
|
| 95 |
return [ |
| 96 |
'success' => false, |
| 97 |
'message' => 'Unable to complete the request. Please try again or adjust your input.', |
| 98 |
]; |
| 99 |
|
| 100 |
} |
| 101 |
|
| 102 |
return [ |
| 103 |
'success' => true, |
| 104 |
'data' => $decoded |
| 105 |
]; |
| 106 |
|
| 107 |
} |
| 108 |
|
| 109 |
} |
| 110 |
|