PHP code example of screenshotfreeapi / screenshotfreeapi-php
1. Go to this page and download the library: Download screenshotfreeapi/screenshotfreeapi-php 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/ */
screenshotfreeapi / screenshotfreeapi-php example snippets
use ScreenshotFreeAPI\ScreenshotFreeAPIClient;
$client = new ScreenshotFreeAPIClient('sfa_your_api_key_here');
// Capture a screenshot and wait for the result
$result = $client->capture('https://stripe.com/pricing');
echo $result['screenshots'][0]['url'];
// https://s3.amazonaws.com/snapshots/...?X-Amz-Expires=900
$client = new ScreenshotFreeAPIClient('sfa_your_api_key_here');
$tokenResponse = $client->auth->token('[email protected] ', 'your_password');
$jwt = $tokenResponse['token'];
// Use the JWT for billing calls
$plan = $client->billing->plan($jwt);
// Basic
$job = $client->screenshots->web(['url' => 'https://example.com']);
$result = $client->screenshots->wait($job['jobId']);
// With options
$job = $client->screenshots->web([
'url' => 'https://stripe.com/pricing',
'description' => 'the pricing comparison table', // AI targeting
'format' => 'png',
'fullPage' => true,
'dimensions' => ['width' => 1440, 'height' => 900],
'blockAds' => true,
'acceptCookies' => true,
'webhookUrl' => 'https://your-app.com/webhook',
]);
// Or capture and wait in one call
$result = $client->screenshots->webAndWait([
'url' => 'https://github.com',
'format' => 'jpeg',
]);
echo $result['screenshots'][0]['url'];
$result = $client->screenshots->mobileAndWait([
'appName' => 'Instagram',
'platform' => 'both', // 'ios', 'android', or 'both'
'
$html = '<html><body style="background:hotpink;padding:40px"><h1>Hello!</h1></body></html>';
$result = $client->screenshots->htmlAndWait([
'html' => $html,
'format' => 'png',
'dimensions' => ['width' => 800, 'height' => 400],
]);
echo $result['screenshots'][0]['url'];
$result = $client->capture('https://news.ycombinator.com', [
'format' => 'png',
'fullPage' => true,
]);
use ScreenshotFreeAPI\Exceptions\JobFailedException;
use ScreenshotFreeAPI\Exceptions\JobTimeoutException;
// Submit (non-blocking, returns immediately with jobId)
$job = $client->screenshots->web([
'url' => 'https://vercel.com',
'webhookUrl' => 'https://your-app.com/webhook', // optional
]);
echo "Job ID: " . $job['jobId'] . PHP_EOL;
echo "Estimated: " . $job['estimatedSeconds'] . "s" . PHP_EOL;
// Poll status manually
while (true) {
$status = $client->jobs->status($job['jobId']);
echo "Status: " . $status['status'] . " (" . $status['progress'] . "%)";
if ($status['status'] === 'completed') {
$result = $client->jobs->result($job['jobId']);
echo $result['screenshots'][0]['url'];
break;
}
if ($status['status'] === 'failed') {
echo "Failed: " . $status['error'];
break;
}
sleep(2);
}
$result = $client->screenshots->wait(
jobId: $job['jobId'],
pollIntervalMs: 2000,
timeoutMs: 120000,
onProgress: function (array $status): void {
printf("[%s] %d%%\n", $status['status'], $status['progress']);
}
);
use ScreenshotFreeAPI\Exceptions\AuthenticationException;
use ScreenshotFreeAPI\Exceptions\ForbiddenException;
use ScreenshotFreeAPI\Exceptions\JobFailedException;
use ScreenshotFreeAPI\Exceptions\JobTimeoutException;
use ScreenshotFreeAPI\Exceptions\NotFoundException;
use ScreenshotFreeAPI\Exceptions\PaymentRequiredException;
use ScreenshotFreeAPI\Exceptions\QuotaExceededException;
use ScreenshotFreeAPI\Exceptions\RateLimitException;
use ScreenshotFreeAPI\Exceptions\ScreenshotFreeAPIException;
use ScreenshotFreeAPI\Exceptions\ValidationException;
try {
$result = $client->capture('https://example.com');
} catch (AuthenticationException $e) {
// 401 — invalid or missing API key
echo "Auth error: " . $e->getMessage();
} catch (ForbiddenException $e) {
// 403 — key revoked or account suspended
echo "Forbidden: " . $e->getMessage();
} catch (PaymentRequiredException $e) {
// 402 — subscription cancelled or payment overdue
echo "Payment APIException $e) {
// Catch-all for any other ScreenshotFreeAPI error (5xx etc.)
echo "API error [HTTP " . $e->getStatusCode() . "]: " . $e->getMessage();
}
// List plans (no auth ing->plans();
// Current plan and usage (JWT ;
$plan = $client->billing->plan($jwt);
echo $plan['tier'] . ": " . $plan['screenshotsUsed'] . " used";
// 30-day usage history
$usage = $client->billing->usage($jwt);
// Upgrade plan (returns Flutterwave checkout URL)
$checkout = $client->billing->upgrade($jwt, ['plan' => 'GROWTH']);
echo $checkout['checkoutUrl'];
// Cancel subscription
$client->billing->cancel($jwt);
$jwt = $client->auth->token('[email protected] ', 'password')['token'];
// Create workspace
$ws = $client->workspaces->create($jwt, ['name' => 'Acme Team']);
// List workspaces
$list = $client->workspaces->list($jwt);
// Invite a member
$client->workspaces->invite($jwt, $ws['id'], '[email protected] ', 'member');
// Change role
$client->workspaces->updateMemberRole($jwt, $ws['id'], $userId, 'admin');
// Remove member
$client->workspaces->removeMember($jwt, $ws['id'], $userId);
$jwt = $client->auth->token('[email protected] ', 'password')['token'];
// Create a monitor (cron: every hour)
$monitor = $client->monitors->create($jwt, [
'appName' => 'Instagram',
'platform' => 'both',
'schedule' => '0 * * * *',
'webhookUrl' => 'https://your-app.com/monitor-webhook',
]);
// List monitors
$monitors = $client->monitors->list($jwt);
// Fetch run history with diffs
$history = $client->monitors->history($jwt, $monitor['id'], ['limit' => 10]);
// Delete a monitor
$client->monitors->delete($jwt, $monitor['id']);
// Register a webhook for Zapier
$sub = $client->integrations->zapierSubscribe(
'https://hooks.zapier.com/hooks/catch/xxx/yyy',
'screenshot.completed'
);
// Get a sample payload for Zap setup
$sample = $client->integrations->zapierTriggerSample('screenshot.completed');
// Unsubscribe
$client->integrations->zapierUnsubscribe($sub['subscriptionId']);
$rawBody = file_get_contents('php://input');
$sig = $_SERVER['HTTP_X_SCREENSHOTFREE_SIGNATURE'] ?? '';
$secret = $_ENV['SCREENSHOTFREEAPI_WEBHOOK_SECRET'];
use ScreenshotFreeAPI\Webhooks;
if (!Webhooks::verifySignature($rawBody, $sig, $secret)) {
http_response_code(401);
exit('Invalid signature');
}
$event = json_decode($rawBody, true);
if ($event['event'] === 'screenshot.completed') {
$jobId = $event['jobId'];
// fetch result, save to DB, notify user, etc.
}
http_response_code(200);
// app/Http/Middleware/VerifyScreenshotFreeAPIWebhook.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use ScreenshotFreeAPI\Webhooks;
class VerifyScreenshotFreeAPIWebhook
{
public function handle(Request $request, Closure $next): mixed
{
$sig = $request->header('X-ScreenshotFree-Signature', '');
$secret = config('services.screenshotfreeapi.webhook_secret');
if (!Webhooks::verifySignature($request->getContent(), $sig, $secret)) {
abort(401, 'Invalid ScreenshotFreeAPI webhook signature.');
}
return $next($request);
}
}
// Route definition
Route::post('/webhooks/screenshot-events', ScreenshotFreeAPIWebhookController::class)
->middleware(VerifyScreenshotFreeAPIWebhook::class);
$client = new ScreenshotFreeAPIClient(
apiKey: 'sfa_your_key',
baseUrl: 'https://api.screenshotfreeapi.com', // override for testing/proxy
timeout: 30, // cURL timeout in seconds
maxRetries: 3 // max retry attempts (429 + 5xx)
);
$status = $client->health();
// ['status' => 'ok', 'version' => '2.0.0', ...]
bash
composer