Skip to main content

PHP SDK

The Mobiscroll Connect PHP SDK provides a convenient way to integrate Mobiscroll Connect in PHP backends.

Setup​

Install the package using Composer:

composer require mobiscroll/connect-php

Client Initialization​

To use the SDK, initialize MobiscrollConnectClient with your client credentials.

Class: Mobiscroll\Connect\MobiscrollConnectClient

constructorMobiscrollConnectClient::__construct

Constructor arguments.

clientIdstring

Your Client ID obtained from the Mobiscroll Connect dashboard.

clientSecretstring

Your Client Secret obtained from the Mobiscroll Connect dashboard.

redirectUristring

Your application's redirect URI that matches the one configured in the Mobiscroll Connect dashboard.

Usage:

<?php

use Mobiscroll\Connect\MobiscrollConnectClient;

$client = new MobiscrollConnectClient(
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
redirectUri: 'YOUR_REDIRECT_URI'
);

Methods​

setCredentials​

Sets the access token for the client. This is required before making any API calls that require authentication.

Method: client->auth()->setCredentials(tokens)

tokensTokenResponse

The token response object returned by client->auth()->getToken(code).

onTokensRefreshed​

Registers a callback to be invoked whenever the SDK automatically refreshes the access token. Use this to persist the updated tokens so they survive future requests.

Method: client->onTokensRefreshed(callback)

callbackcallable(TokenResponse): void

A callable that receives the updated TokenResponse after a successful automatic token refresh.

Token Refresh​

The PHP SDK handles token refresh automatically. When any API call returns a 401 Unauthorized response and the client has a refresh_token stored, the SDK will silently exchange it for a new access token and retry the original request — with no action required from your application.

When the refresh succeeds, the SDK invokes your onTokensRefreshed callback with the updated TokenResponse. You must register this callback and persist the new tokens, otherwise they will be lost between requests.

use Mobiscroll\Connect\TokenResponse;

$client->onTokensRefreshed(function (TokenResponse $updatedTokens) {
// Persist $updatedTokens in your database or session store
// so the new access_token and refresh_token survive future requests
$_SESSION['tokens'] = $updatedTokens->toArray();
});

If the refresh token itself is invalid or has been revoked, the SDK throws an AuthenticationError and the user must re-authorize.

Error Handling​

All SDK methods throw exceptions that extend Mobiscroll\Connect\Exceptions\MobiscrollConnectException. You can catch the base exception or any of the specific subclasses.

ExceptionHTTP StatusgetCodeString()
AuthenticationError401, 403AUTHENTICATION_ERROR
CalendarPermissionError403CALENDAR_PERMISSION_REQUIRED
ValidationError400, 422VALIDATION_ERROR
NotFoundError404NOT_FOUND_ERROR
RateLimitError429RATE_LIMIT_ERROR
ServerError5xxSERVER_ERROR
NetworkError—NETWORK_ERROR

ValidationError exposes a getDetails() method that returns field-level validation errors. RateLimitError exposes getRetryAfter() (seconds) and ServerError exposes getStatusCode().

use Mobiscroll\Connect\Exceptions\{
AuthenticationError,
ValidationError,
RateLimitError,
MobiscrollConnectException,
};

try {
$events = $client->events()->list(['start' => new DateTime('2024-01-01')]);
} catch (AuthenticationError $e) {
// Token expired or invalid — refresh manually or re-authorize the user
} catch (ValidationError $e) {
// Invalid request parameters
$details = $e->getDetails();
} catch (RateLimitError $e) {
$retryAfter = $e->getRetryAfter(); // seconds
} catch (MobiscrollConnectException $e) {
// Catch-all for any other SDK error
}

Auth API​

The client->auth() resource handles the OAuth authorization flow, including generating authorization URLs, exchanging codes for tokens, managing connection status, and disconnecting providers.

Each account returned by getConnectionStatus reports grantedScopes and calendarPermissionGranted. A false flag means the account connected but withheld calendar access on the provider's consent screen, so it can list no calendars until the user reconnects — see Partial consent. Each account also reports syncState: reauth_required means the provider has since rejected the stored credentials and the account has stopped syncing — a different question from calendarPermissionGranted, which only records what was agreed at connect time. See Connection health.

When no connected account has calendar access, calendar and event calls raise CalendarPermissionError — getAccounts() names the accounts that must reconnect. It subclasses AuthenticationError, so existing handlers keep working.

To localize the Connect pages, pass an optional lng to generateAuthUrl, e.g. generateAuthUrl(userId: ..., lng: 'es'). When omitted, the UI falls back to the browser's Accept-Language header, then English; Arabic, Hebrew and Persian render right-to-left. See Supported languages for the languages Connect supports.


auth()->generateAuthUrl​

Builds the URL that starts the authorization flow. Redirect the user to it: once they connect their calendars, Connect redirects them back to your redirect URI with an authorization code. The URL is built locally, without an API request. See GET /authorize.

Method: client->auth()->generateAuthUrl(userId, scope, state, lng)

Returns: string

userIdstring

Your identifier for the user. scope, state and lng are optional; pass them as named arguments.

Usage:

// Generate the authorization URL
$authUrl = $client->auth()->generateAuthUrl(
userId: 'user-456',
// Optional parameters:
// scope: 'read-write',
// state: 'xyz789',
// lng: 'es', // localize the Connect pages
);

// Redirect the user to $authUrl
header('Location: ' . $authUrl);

auth()->getToken​

Exchanges the authorization code from your redirect URI for an access token and a refresh token. The PHP SDK does not store the returned tokens on the client — pass them to setCredentials before calling other methods. See POST /token.

Method: client->auth()->getToken(code)

Returns: TokenResponse

codestring

The authorization code received on your redirect URI.

Usage:

// Exchange authorization code for access token
$code = $_GET['code'];
$tokenResponse = $client->auth()->getToken($code);

// Store the token and authenticate the client
$client->auth()->setCredentials($tokenResponse);

Calendars API​

The client->calendars() resource allows you to list available calendars from all connected providers (Google, Outlook, etc.). It corresponds to the /calendars endpoints.


calendars()->list​

Lists the calendars of every account the user has connected. See GET /calendars.

Method: client->calendars()->list()

Returns: array

Usage:

$calendars = $client->calendars()->list();

Events API​

The client->events() resource provides methods to create, read, update, and delete calendar events across all connected accounts. It corresponds to the /events endpoints.


events()->list​

Lists events from the user's calendars, one page at a time. When the response contains a nextPageToken, pass it to the next call to get the following page. See GET /events.

Method: client->events()->list(params)

Returns: array — events, and nextPageToken when more pages are available.

paramsarray

All keys are optional: start, end, calendarIds (calendar IDs grouped by provider), pageSize, nextPageToken and singleEvents.

Usage:

// Fetch initial events with date range filter
$response = $client->events()->list([
'pageSize' => 50,
'start' => '2025-10-01T00:00:00Z',
'end' => '2025-10-31T23:59:59Z',
]);
$events = $response['events'];

// Load more events using nextPageToken
$nextResponse = $client->events()->list([
'pageSize' => 50,
'nextPageToken' => $response['nextPageToken'] ?? null,
]);

// Filter by specific calendars
$filteredEvents = $client->events()->list([
'pageSize' => 25,
'calendarIds' => ['google' => ['personal@gmail.com', 'work@company.com']],
]);

// Get recurring event series masters (not expanded)
$masters = $client->events()->list([
'pageSize' => 50,
'singleEvents' => false,
]);

events()->create​

Creates an event in the given calendar. Set recurrence to create a recurring series. See POST /event.

Method: client->events()->create(event)

Returns: CalendarEvent

eventarray

The event fields, using the API field names. provider, calendarId, title, start and end are required. Optional fields include description, location, allDay and recurrence.

Usage:

// Create a simple event
$event = $client->events()->create([
'provider' => 'google',
'calendarId' => 'primary',
'title' => 'Team Meeting',
'description' => 'Discuss project updates',
'start' => '2025-11-01T10:00:00Z',
'end' => '2025-11-01T11:00:00Z',
'location' => 'Conference Room A',
]);

// Create a recurring event
$recurringEvent = $client->events()->create([
'provider' => 'microsoft',
'calendarId' => 'AAMkAGVmMDEz...',
'title' => 'Weekly Standup',
'start' => '2025-11-01T09:00:00Z',
'end' => '2025-11-01T09:30:00Z',
'allDay' => false,
'recurrence' => [
'frequency' => 'WEEKLY',
'interval' => 1,
'count' => 10,
'byDay' => ['MO', 'WE', 'FR'],
],
]);

// Create an all-day event
$allDayEvent = $client->events()->create([
'provider' => 'apple',
'calendarId' => 'https://caldav.icloud.com/.../calendars/...',
'title' => 'Conference',
'start' => '2025-11-15T00:00:00Z',
'end' => '2025-11-16T00:00:00Z',
'allDay' => true,
'description' => 'Annual tech conference',
]);

events()->update​

Updates an existing event. For an occurrence of a recurring series, set recurringEventId, and use updateMode to choose which occurrences change: this, following or all. See PUT /event.

Method: client->events()->update(event)

Returns: CalendarEvent

eventarray

provider, calendarId and eventId, plus the fields you want to change. Add recurringEventId and updateMode for recurring events.

Usage:

// Update a simple event
$updatedEvent = $client->events()->update([
'provider' => 'google',
'calendarId' => 'primary',
'eventId' => 'event123abc',
'title' => 'Updated Team Meeting',
'start' => '2025-11-01T14:00:00Z',
'end' => '2025-11-01T15:00:00Z',
]);

// Update a single instance of a recurring event
$updatedInstance = $client->events()->update([
'provider' => 'microsoft',
'eventId' => 'instance456',
'recurringEventId' => 'series123',
'calendarId' => 'AAMkAGVmMDEz...',
'updateMode' => 'this',
'title' => 'Standup - Special Topic Today',
'start' => '2025-11-01T09:00:00Z',
'end' => '2025-11-01T10:00:00Z',
]);

// Update all future occurrences
$updatedFuture = $client->events()->update([
'provider' => 'apple',
'eventId' => 'recurring-event-id',
'calendarId' => 'https://caldav.icloud.com/.../calendars/...',
'updateMode' => 'following',
'location' => 'New Conference Room B',
]);

events()->delete​

Deletes an event. For an occurrence of a recurring series, set recurringEventId, and use deleteMode to choose which occurrences are deleted: this, following or all. See DELETE /event.

Method: client->events()->delete(params)

Returns: array

paramsarray

provider, calendarId and eventId are required. recurringEventId and deleteMode are optional.

Usage:

// Delete a simple event
$client->events()->delete([
'provider' => 'google',
'calendarId' => 'primary',
'eventId' => 'event123abc',
]);

// Delete a single instance of a recurring event
$client->events()->delete([
'provider' => 'microsoft',
'calendarId' => 'AAMkAGVmMDEz...',
'eventId' => 'instance456',
'recurringEventId' => 'series123',
'deleteMode' => 'this',
]);

// Delete entire recurring series
$client->events()->delete([
'provider' => 'apple',
'calendarId' => 'https://caldav.icloud.com/.../calendars/...',
'eventId' => 'recurring-event-id',
'deleteMode' => 'all',
]);

Webhooks API​

The client->webhooks() resource lets you subscribe a calendar to change notifications and unsubscribe an existing channel. It corresponds to the /subscribe-webhook and /unsubscribe-webhook endpoints. Connect subscribes and renews channels automatically when a calendar is connected — this resource is for managing a specific channel explicitly.


webhooks()->subscribeWebhook​

Subscribes a calendar to change notifications. See POST /subscribe-webhook.

Method: client->webhooks()->subscribeWebhook(params)

Returns: SubscribeWebhookResponse

paramsarray

provider and calendarId are required. channelId is optional and generated by the server when omitted. expiration is an optional Unix timestamp in milliseconds.

Usage:

$subscription = $client->webhooks()->subscribeWebhook([
'provider' => 'google',
'calendarId' => 'work@company.com',
'channelId' => 'my-channel-123',
]);

webhooks()->unsubscribeWebhook​

Removes an existing webhook subscription. See POST /unsubscribe-webhook.

Method: client->webhooks()->unsubscribeWebhook(params)

Returns: UnsubscribeWebhookResponse

paramsarray

provider and channelId are required. resourceId is the provider resource ID returned by subscribeWebhook, where the provider uses one.

Usage:

$client->webhooks()->unsubscribeWebhook([
'provider' => 'google',
'channelId' => 'my-channel-123',
'resourceId' => 'resource-abc',
]);