PHP code example of stitch-digital / simpro-php-sdk
1. Go to this page and download the library: Download stitch-digital/simpro-php-sdk library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
stitch-digital / simpro-php-sdk example snippets
use Simpro\PhpSdk\Simpro\Connectors\SimproApiKeyConnector;
// For server-to-server integrations
$connector = new SimproApiKeyConnector(
baseUrl: 'https://example.simprosuite.com/api/v1.0',
apiKey: 'your-api-key'
);
// Get information about your Simpro instance
$version = $connector->info()->version(); // Returns: '99.0.0.0.1.1'
// List all companies
$companies = $connector->companies()->list();
foreach ($companies->items() as $company) {
echo "{$company->id}: {$company->name}\n";
}
use Simpro\PhpSdk\Simpro\Connectors\SimproOAuthConnector;
// Create the connector
$connector = new SimproOAuthConnector(
baseUrl: 'https://example.simprosuite.com',
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
redirectUri: 'https://yourapp.com/oauth/callback'
);
// Step 1: Redirect user to authorization URL
$authUrl = $connector->getAuthorizationUrl();
// Redirect user to $authUrl
// Step 2: In your callback handler, exchange the code for a token
$code = $_GET['code']; // From the callback URL
$authenticator = $connector->getAccessToken($code);
// Step 3: Authenticate your connector and store the authenticator
$connector->authenticate($authenticator);
// Store $authenticator->serialize() securely (encrypted in database)
// so you can reuse it later
// Step 4: Make API requests
$version = $connector->info()->version();
// Step 5: Check for expired tokens and refresh when needed
if ($authenticator->hasExpired()) {
$newAuthenticator = $connector->refreshAccessToken($authenticator);
// Update stored authenticator
}
// Serializing for storage
$serialized = $authenticator->serialize();
// Unserializing when retrieving
use Saloon\Http\Auth\AccessTokenAuthenticator;
$authenticator = AccessTokenAuthenticator::unserialize($serialized);
use Simpro\PhpSdk\Simpro\Connectors\SimproApiKeyConnector;
// Create the connector
$connector = new SimproApiKeyConnector(
baseUrl: 'https://example.simprosuite.com/api/v1.0',
apiKey: 'your-api-key'
);
// Make API requests - authentication is handled automatically
$version = $connector->info()->version();
// No configuration needed - rate limiting works out of the box
$connector = new SimproApiKeyConnector(
baseUrl: 'https://example.simprosuite.com/api/v1.0',
apiKey: 'your-api-key'
);
use Saloon\RateLimitPlugin\Stores\FileStore;
use Simpro\PhpSdk\Simpro\RateLimit\RateLimitConfig;
// File-based store for persistence across processes
$connector = new SimproApiKeyConnector(
baseUrl: 'https://example.simprosuite.com/api/v1.0',
apiKey: 'your-api-key',
rateLimitConfig: new RateLimitConfig(
store: new FileStore('/var/cache/simpro'),
),
);
use Saloon\RateLimitPlugin\Stores\LaravelCacheStore;
use Simpro\PhpSdk\Simpro\RateLimit\RateLimitConfig;
// Use Laravel's Redis cache for distributed rate limiting
$connector = new SimproApiKeyConnector(
baseUrl: 'https://example.simprosuite.com/api/v1.0',
apiKey: 'your-api-key',
rateLimitConfig: new RateLimitConfig(
store: new LaravelCacheStore(Cache::store('redis')),
),
);
use Saloon\RateLimitPlugin\Exceptions\RateLimitReachedException;
use Simpro\PhpSdk\Simpro\RateLimit\RateLimitConfig;
$connector = new SimproApiKeyConnector(
baseUrl: 'https://example.simprosuite.com/api/v1.0',
apiKey: 'your-api-key',
rateLimitConfig: RateLimitConfig::throwing(),
);
try {
$response = $connector->send($request);
} catch (RateLimitReachedException $e) {
// Release job back to queue with delay
$secondsToWait = $e->getLimit()->getRemainingSeconds();
// ... release job with $secondsToWait delay
}
$connector = new SimproApiKeyConnector(
baseUrl: 'https://example.simprosuite.com/api/v1.0',
apiKey: 'your-api-key'
);
$connector->useRateLimitPlugin(false);
use Simpro\PhpSdk\Simpro\Cache\CacheConfig;
// Using PSR-16 cache (e.g., Symfony Cache)
$connector = new SimproApiKeyConnector(
baseUrl: 'https://example.simprosuite.com/api/v1.0',
apiKey: 'your-api-key',
cacheConfig: CacheConfig::psr16($symfonyCache),
);
// Using Laravel cache
$connector = new SimproApiKeyConnector(
baseUrl: 'https://example.simprosuite.com/api/v1.0',
apiKey: 'your-api-key',
cacheConfig: CacheConfig::laravel(Cache::store('redis')),
);
// Using Flysystem
$connector = new SimproApiKeyConnector(
baseUrl: 'https://example.simprosuite.com/api/v1.0',
apiKey: 'your-api-key',
cacheConfig: CacheConfig::flysystem($filesystem),
);
use Illuminate\Support\Facades\Cache;
use Saloon\RateLimitPlugin\Stores\LaravelCacheStore;
use Simpro\PhpSdk\Simpro\Cache\CacheConfig;
use Simpro\PhpSdk\Simpro\Connectors\SimproApiKeyConnector;
use Simpro\PhpSdk\Simpro\RateLimit\RateLimitConfig;
public function register(): void
{
$this->app->singleton(SimproApiKeyConnector::class, function ($app) {
return new SimproApiKeyConnector(
baseUrl: config('services.simpro.base_url'),
apiKey: config('services.simpro.api_key'),
requestTimeout: 30,
rateLimitConfig: new RateLimitConfig(
store: new LaravelCacheStore($app['cache']->store()),
),
cacheConfig: CacheConfig::laravel(
cache: Cache::store('redis'),
expiryInSeconds: 300,
),
);
});
}
use Simpro\PhpSdk\Simpro\Connectors\SimproApiKeyConnector;
class JobController extends Controller
{
public function __construct(
private SimproApiKeyConnector $simpro
) {}
public function index()
{
$jobs = $this->simpro->jobs()->list()->all();
return view('jobs.index', compact('jobs'));
}
}
namespace App\Services;
use App\Models\SimproConnection;
use Illuminate\Support\Facades\Cache;
use Saloon\RateLimitPlugin\Stores\LaravelCacheStore;
use Simpro\PhpSdk\Simpro\Cache\CacheConfig;
use Simpro\PhpSdk\Simpro\Connectors\SimproOAuthConnector;
use Simpro\PhpSdk\Simpro\RateLimit\RateLimitConfig;
class SimproConnectorFactory
{
/**
* Create an unauthenticated connector for the OAuth flow.
*/
public function make(string $buildUrl): SimproOAuthConnector
{
return new SimproOAuthConnector(
baseUrl: $buildUrl,
clientId: config('services.simpro.client_id'),
clientSecret: config('services.simpro.client_secret'),
redirectUri: config('services.simpro.redirect_uri'),
scopes: [],
requestTimeout: 30,
rateLimitConfig: new RateLimitConfig(
store: new LaravelCacheStore(Cache::store()),
),
cacheConfig: CacheConfig::laravel(
cache: Cache::store('redis'),
expiryInSeconds: 300,
),
);
}
/**
* Create an authenticated connector from a stored connection.
*/
public function authenticated(SimproConnection $connection): SimproOAuthConnector
{
$connector = $this->make($connection->build_url);
$authenticator = $connection->simpro_auth;
// Refresh the token if expired
if ($authenticator->hasExpired()) {
$authenticator = $connector->refreshAccessToken($authenticator);
$connection->update(['simpro_auth' => $authenticator]);
}
$connector->authenticate($authenticator);
return $connector;
}
}
namespace App\Http\Controllers;
use App\Models\SimproConnection;
use App\Services\SimproConnectorFactory;
use Illuminate\Http\Request;
class SimproOAuthController extends Controller
{
public function __construct(
private SimproConnectorFactory $factory
) {}
public function redirect(Request $request)
{
$request->validate(['build_url' => 'or = $this->factory->make($buildUrl);
$authenticator = $connector->getAccessToken($request->code);
SimproConnection::updateOrCreate(
['user_id' => $request->user()->id],
[
'build_url' => $buildUrl,
'simpro_auth' => $authenticator,
]
);
return redirect()->route('dashboard')
->with('success', 'Simpro account connected successfully.');
}
}
use App\Models\SimproConnection;
use App\Services\SimproConnectorFactory;
class SyncJobsCommand extends Command
{
public function handle(SimproConnectorFactory $factory): void
{
$connections = SimproConnection::all();
foreach ($connections as $connection) {
$simpro = $factory->authenticated($connection);
foreach ($simpro->jobs()->list()->items() as $job) {
// Process each job...
}
}
}
}
use Saloon\Exceptions\Request\ClientException;
use Saloon\Exceptions\Request\ServerException;
use Simpro\PhpSdk\Simpro\Exceptions\ValidationException;
try {
// Make an API request
$response = $connector->send($request);
} catch (ValidationException $exception) {
// Handle validation errors (422)
// Get a string describing all errors
$message = $exception->getMessage();
// Get all validation errors as an array
$errors = $exception->getErrors();
// ['field_name' => ['Error message 1', 'Error message 2']]
// Get errors for a specific field
$fieldErrors = $exception->getErrorsForField('field_name');
// Check if a specific field has errors
$hasErrors = $exception->hasErrorsForField('field_name');
// Get all error messages as a flat array
$allMessages = $exception->getAllErrorMessages();
// Access the Saloon Response object for debugging
$response = $exception->getResponse();
} catch (ClientException $exception) {
// Handle 4xx errors (401, 403, 404, etc.)
$message = $exception->getMessage();
$response = $exception->getResponse();
} catch (ServerException $exception) {
// Handle 5xx errors
$message = $exception->getMessage();
$response = $exception->getResponse();
}
// List all companies (returns QueryBuilder)
$companies = $connector->companies()->list();
// Iterate over all items across all pages
foreach ($companies->items() as $company) {
echo "{$company->id}: {$company->name}\n";
}
// Or get the first result
$first = $connector->companies()->list()->first();
// Or get all results as an array
$all = $connector->companies()->list()->all();