Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions api_v2/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Blesta SDK V2 (Beta)

This repository contains a simple SDK for interacting with the Blesta API. The SDK is written in PHP and provides an easy way to make API requests and handle responses.

---

## Files Overview

### `blesta_api.php`
This is the main SDK file that handles communication with the Blesta API. It includes two classes:

1. **BlestaApi**:
- Handles API requests (`GET`, `POST`, `PUT`, `DELETE`) to the Blesta API.
- Supports SSL verification and debug mode.
- Provides methods to retrieve the last request details and parse API responses.

2. **BlestaResponse**:
- Handles the response from the Blesta API.
- Provides methods to access the raw response, parsed response, and any errors.

#### Key Features:
- **API Request Methods**:
- `get($model, $method, $args = [])`
- `post($model, $method, $args = [])`
- `put($model, $method, $args = [])`
- `delete($model, $method, $args = [])`
- **Response Handling**:
- `response()` - Returns the parsed response.
- `errors()` - Returns any errors in the response.
- `raw()` - Returns the raw response as a string.
- **Debug Mode**:
- When enabled, prints detailed request and response information.

---

### `config.php`
This file contains the configuration for the Blesta API. It is used to store API credentials and settings.

#### Configuration Options:
- **`url`**: The base URL of the Blesta API (e.g., `https://yourdomain.com/api/`).
- **`user`**: The API username.
- **`key`**: The API key.
- **`ssl_verify`**: A boolean value to enable or disable SSL verification (`true` by default).
- **`debug`**: A boolean value to enable or disable debug mode (`false` by default).

#### Example Configuration:
```php
return [
'url' => 'https://yourdomain.com/api/',
'user' => 'YOUR_API_USER',
'key' => 'YOUR_API_KEY',
'ssl_verify' => true,
'debug' => false,
];
177 changes: 177 additions & 0 deletions api_v2/blesta_api.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
<?php
/**
* Blesta API processor v2.0
*
* @copyright Copyright (c) 2013, Phillips Data, Inc.
* @license http://opensource.org/licenses/mit-license.php MIT License
* @package blesta_sdk
*/

require_once "config.php";

/**
* Blesta API response handler
*
* Handles the response from the Blesta API.
*/
class BlestaResponse
{
private string $raw;
private int $response_code;

public function __construct(string $response, int $response_code)
{
$this->raw = $response;
$this->response_code = $response_code;
}

public function response(): mixed
{
$response = $this->formatResponse();
return $response->response ?? null;
}

public function responseCode(): int
{
return $this->response_code;
}

public function raw(): string
{
return $this->raw;
}

public function errors(): stdClass|false
{
if ($this->response_code !== 200) {
$response = $this->formatResponse();

if (isset($response->errors)) {
return $response->errors;
}

$error = new stdClass();
$error->error = $response;
return $error;
}

return false;
}

private function formatResponse(): ?stdClass
{
return json_decode($this->raw);
}
}

/**
* Blesta API processor
*
* Handles communication with the Blesta API.
*/
class BlestaApi
{
private string $url;
private string $user;
private string $key;
private bool $ssl_verify;
private bool $debug;
private ?array $last_request = null;
private const FORMAT = "json";

/**
* Initializes the API with configuration.
*
* @param array $config Configuration array containing:
* - url: The URL to the Blesta API
* - user: The API user
* - key: The API key
* - ssl_verify: Whether to enforce SSL verification (default: true)
* - debug: Whether to enable debug mode (default: false)
*/
public function __construct(array $config)
{
$this->url = $config['url'] ?? throw new InvalidArgumentException("API URL is required.");
$this->user = $config['user'] ?? throw new InvalidArgumentException("API user is required.");
$this->key = $config['key'] ?? throw new InvalidArgumentException("API key is required.");
$this->ssl_verify = $config['ssl_verify'] ?? true;
$this->debug = $config['debug'] ?? false;
}

public function get(string $model, string $method, array $args = []): BlestaResponse
{
return $this->submit($model, $method, $args, "GET");
}

public function post(string $model, string $method, array $args = []): BlestaResponse
{
return $this->submit($model, $method, $args, "POST");
}

public function put(string $model, string $method, array $args = []): BlestaResponse
{
return $this->submit($model, $method, $args, "PUT");
}

public function delete(string $model, string $method, array $args = []): BlestaResponse
{
return $this->submit($model, $method, $args, "DELETE");
}

private function submit(string $model, string $method, array $args = [], string $action = "POST"): BlestaResponse
{
$url = $this->url . $model . "/" . $method . "." . self::FORMAT;

$this->last_request = [
'url' => $url,
'args' => $args
];

if ($action === "GET") {
$url .= "?" . http_build_query($args);
$args = null;
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $action);
curl_setopt($ch, CURLOPT_URL, $url);

if ($args) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($args));
}

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "{$this->user}:{$this->key}");

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->ssl_verify);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $this->ssl_verify ? 2 : 0);

$response = curl_exec($ch);
$response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($response === false) {
$error = curl_error($ch);
curl_close($ch);
throw new RuntimeException("cURL error: $error");
}

curl_close($ch);

if ($this->debug) {
echo "Debug Info:\n";
echo "URL: $url\n";
echo "Action: $action\n";
echo "Response Code: $response_code\n";
echo "Response: $response\n";
}

return new BlestaResponse($response, $response_code);
}

public function lastRequest(): ?array
{
return $this->last_request;
}
}
?>
13 changes: 13 additions & 0 deletions api_v2/config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

/**
* Configuration for Blesta API
*/
return [
'url' => 'https://example.com/api/',
'user' => '',
'key' => '',
'ssl_verify' => true, // Set to false to disable SSL verification
'debug' => false, // Set to true to enable debug mode
];
?>
38 changes: 38 additions & 0 deletions api_v2/example.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php
require_once "blesta_api.php";
$config = require "config.php";

// Initialize the Blesta API
$api = new BlestaApi($config);

try {
// Example API call: Fetch user details
$response = $api->get("users", "get", ['user_id' => 1]);

// Parse and format the response
$data = $response->response();
$errors = $response->errors();

if ($data) {
echo "Parsed Response:\n";
echo "ID: " . ($data->id ?? "N/A") . "\n";
echo "Username: " . ($data->username ?? "N/A") . "\n";
// echo "Password (hashed): " . ($data->password ?? "N/A") . "\n";
echo "Recovery Email: " . (!empty($data->recovery_email) ? $data->recovery_email : "Not set") . "\n";
echo "Two-Factor Mode: " . ($data->two_factor_mode ?? "N/A") . "\n";
// echo "Two-Factor Key: " . ($data->two_factor_key ?? "N/A") . "\n";
// echo "Two-Factor PIN: " . (!empty($data->two_factor_pin) ? $data->two_factor_pin : "Not set") . "\n";
echo "Date Added: " . ($data->date_added ?? "N/A") . "\n";
} else {
echo "No response data available.\n";
}

// Display errors if any
if ($errors) {
echo "\nErrors:\n";
print_r($errors);
}
} catch (Exception $e) {
echo "An error occurred: " . $e->getMessage();
}
?>