PHP SDK for the Intelligence Cloud partner API: customer accounts and conversation intelligence.
Requires
- php: >=8.2
- ext-json: *
- guzzlehttp/guzzle: ^7.5
Requires (Dev)
- phpunit/phpunit: ^10.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-30 05:07:44 UTC
README
PHP client for the Intelligence Cloud partner API (https://app.intelligence.cloud/api/v1).
- Customers with an administrator login: the account layer (
$ic->accounts) creates and maintains a customer on Base User and Base Manager licenses, beside one method per API operation (companies, locations, users, products, connectors, First Alert, Insights Hub). - Conversations with a user login: the conversation layer (
$ic->conversations) gives a signed-in person their own calls, tasks and alerts;$ic->intelligencereads calls, transcripts, recordings, alerts, tasks and insights; and the After Call and First Alert webhooks.
Version 0.3.0. PHP 8.2 or later, Composer, Guzzle 7. Changes: CHANGELOG.md.
SDK documentation: overview https://docs.intelligence.cloud/sdk/, quick start https://docs.intelligence.cloud/sdk/quick-start, every helper https://docs.intelligence.cloud/sdk/reference, events https://docs.intelligence.cloud/sdk/events, client options and errors https://docs.intelligence.cloud/sdk/configuration, downloads and versions https://docs.intelligence.cloud/sdk/downloads, testing https://docs.intelligence.cloud/sdk/testing. The API itself: the guide https://docs.intelligence.cloud/api and the API reference https://docs.intelligence.cloud/reference, built from https://docs.intelligence.cloud/openapi.yaml.
Contents
- Install
- Credentials
- Account layer:
$ic->accounts - Conversation layer:
$ic->conversations - Quick start: conversation intelligence
- Rules the SDK applies for you
- Filters and paging
- Errors
- Webhooks (plain PHP and Laravel)
- Testing your code
- Running helpers from more than one process
- How many requests
- Upgrading from 0.2
- Method list
- Examples
Install
composer require intelligence-cloud/sdk
Alternative, from the source download: unzip it into your project and add it as a Composer path repository:
unzip php.zip -d vendor-src composer config repositories.intelligence-cloud path vendor-src/php composer require intelligence-cloud/sdk:0.3.0
Required extensions: json, plus what Guzzle needs (curl recommended).
Credentials
Today every integration signs in with the email and password of a dedicated integration user.
Turn MFA off for that user's company (mfaOff: true in createCustomer, or
$ic->companies->updateCompany($id, ['mfa_enforced' => false])). API keys arrive in December 2026.
Use one client per credential:
| Credential | Role | Use it for |
|---|---|---|
| Admin | reseller_admin |
$ic->accounts, $ic->companies, $ic->users, … |
| Frontline | frontline_user |
$ic->conversations and $ic->intelligence (calls, alerts, tasks, insights) |
Admin logins get empty lists from the conversation-data endpoints by design. $ic->intelligence
checks the role once and throws FrontlineRequiredError instead of returning empty data.
$ic->conversations throws WrongLoginError for an administrator login, and $ic->accounts
throws it for a user login.
Keep credentials out of source code. Read them from your secret store or environment. Send secrets to Tresic only through security@tresic.cloud, and report security issues there too.
use IntelligenceCloud\Client; $admin = new Client(email: getenv('IC_ADMIN_EMAIL'), password: getenv('IC_ADMIN_PASSWORD')); $user = new Client(email: getenv('IC_USER_EMAIL'), password: getenv('IC_USER_PASSWORD'), userAgent: 'riverbend-bi-sync/1.0');
Constructor: new Client(email, password, baseUrl = 'https://app.intelligence.cloud/api/v1', tokenStore = null, timeout = 30, httpClient = null, userAgent = null, sleeper = null, maxRetries = 3, connectorTimeout = 600, loginRateLimitWait = 60, maskNumbers = true, appUrl = 'https://app.intelligence.cloud', deadline = 120, clock = null). userAgent is sent ahead of
the SDK's own; httpClient is any Guzzle ClientInterface; deadline bounds one API request with its
sign-in, renewal, retries and waits (see Retries); clock replaces the clock the deadline
reads. sleeper and clock are test hooks: sleeper (default usleep) is called for every wait (retries, Retry-After, connector checks), clock (default a monotonic clock, in seconds) is read for the deadline; pass your own to run waits instantly or drive time in a test (FakeApi::client() passes a no-op sleeper). connectorTimeout applies to the low-level connector methods only ($client->connectors->createConnector() and the others that wait); the account helpers (createCustomer, addTeam, setConnector) wait as long as the timeout of the ConnectorSpec you give them (default 600 seconds). getenv() returns string|false: check it before you pass it to the SDK, which declares strict types (getenv('X') ?: throw new RuntimeException('X is not set'); the examples cast with (string)). If you pass your own HTTP client, keep certificate verification on. The client never follows redirects, and refuses a baseUrl that is
not https:// (except on localhost).
Reading values. A value is a read-only property ($customer->teams, $err->cause, $seeded->companyId, $api->writes); an action or a lookup with arguments is a method ($api->writesSince($start), $api->count(...)). The older zero-argument methods (cause(), writes(), authLog(), companyId(), callType() and the like) still work and are deprecated.
Sign-in, tokens and sign-out
- The client signs in on first use and keeps the access and refresh tokens in its token store (memory by default).
- Sign-in is limited to 5 per minute. Sign in once per job and reuse the client. On a 429 at
sign-in the client waits once, but only when
Retry-AfterfitsloginRateLimitWait(60 seconds); a longerRetry-AfterthrowsRateLimitErrorat once with$retryAfter. Inside a web request passloginRateLimitWait: 0. - The client renews the access token a minute before it expires, and once after a 401. Refresh tokens are single use: a spent one is never sent again, and the new pair is stored before it is used. A refresh token is sent again only after a 429 (the server did not use it) or after a failure where the request provably never left this machine. After a 5xx, a failure after the request left, or an unreadable answer the client signs in instead: sending a used refresh token ends every session of the login.
- Sign-in needs no extra call:
$ic->login()signs in now and returns the signed-in user. $ic->close()forgets the tokens locally. It does not sign out.$ic->logout()signs out and ends every session of that user, including the web app. The SDK never calls it by itself.- Sign-in returning
mfa_requiredthrowsMfaRequiredError: "Integration users need MFA off for their company. API keys arrive in December 2026." - Sign-in returning
password_expired: truethrowsPasswordExpiredError: a person signs in to the app as the integration user and sets a new password; then update your secret store.
Several workers, one integration user. A refresh token sent twice ends the session everywhere.
The default InMemoryTokenStore is right for one process. When PHP-FPM workers or cron jobs share
an integration user, use IntelligenceCloud\Auth\FileTokenStore. It keeps the tokens in a 0600 file and
serialises sign-in and renewal with a file lock (one machine; for several machines implement
TokenStore over your database, with an advisory lock in withLock):
use IntelligenceCloud\Auth\FileTokenStore; $user = new Client( email: getenv('IC_USER_EMAIL'), password: getenv('IC_USER_PASSWORD'), tokenStore: new FileTokenStore('/var/lib/myapp/ic-tokens.json'), // outside the web root );
To keep tokens in a shared store (a database or cache), implement
IntelligenceCloud\Auth\TokenStore (get, set, withLock). Store tokens like passwords.
Account layer: $ic->accounts (admin)
A customer is one company with one or more teams (each a location in the API) and a
Management location named <Company> - Management.
- Each team has a connector to the phone system, five groups (Customer Threats, Upset Customers, Low Sentiment Calls, Insights Hub Access, Insights Hub Weekly Reports) and three alerts, each routed to its group: Customer Threat (priority high, sentiment below -20 and its phrases), Upset Customer (medium, below -20 and its phrases) and Low Sentiment (low, below -40).
- Management has its own connector, which captures the managers' own lines, and the Insights Hub Weekly Reports group for the company-wide reports. It has no alerts.
- A Base User has After Call on their own line at one team. A Base Manager has all three products, their own line at Management, every Base User line of the teams they run, and those teams' groups.
use IntelligenceCloud\Accounts\{AlertSetting, AlertSettings, ConnectorSpec, CustomerSpec, PersonSpec, TeamSpec}; $phoneSystem = ConnectorSpec::netsapiens('https://pbx.example.com/ns-api/v2', 'riverbend.example.com', $phoneSystemKey); $customer = $admin->accounts->createCustomer(new CustomerSpec( companyName: 'Riverbend Auto Group', admin: new PersonSpec('pat.lee@example.com', 'Pat', 'Lee', phoneNumber: '+15555550100'), team: new TeamSpec('Riverbend - Main', '1 River Rd', 'Springfield', 'IL', 'US', '62701', vertical: '<vertical id or key>'), // from $ic->locations->listVerticals() connector: $phoneSystem, // used for the team and for Management alerts: new AlertSettings( customerThreat: new AlertSetting(phrases: $threatPhrases), // from your Tresic contact upsetCustomer: new AlertSetting(phrases: $upsetPhrases), ), companyId: $savedCompanyId, // null the first time; store $customer->companyId mfaOff: true, // the company has an integration user )); $team = $customer->teams[0]; $admin->accounts->addBaseUser($customer, new PersonSpec('sam.ortiz@example.com', 'Sam', 'Ortiz'), $team, '2101'); $admin->accounts->addBaseManager($customer, new PersonSpec('dana.cho@example.com', 'Dana', 'Cho'), [$team], line: '2001'); $admin->accounts->activateAlerts($customer); // every team; a team with no manager is listed in the result
- Phrase lists come from you. The SDK holds none; ask your Tresic contact for them. A customer
can be created without them: Low Sentiment and every group are created,
$customer->pendinglists"customer_threat"and"upset_customer", andsetAlertscreates those alerts when the lists arrive. - Safe to re-run. Every helper finds what exists before it writes; a second run with the same
input writes nothing. A company is never adopted by its name alone: pass
companyIdfrom the first run. Without it, a same-named company is used only when its primary contact email isadmin.email; otherwiseConflictError($errorCodecompany_name_conflict) is thrown before anything is written. - A
Customerstays current. Its public fields read through to the live state: after$admin->accounts->addTeam($customer, ...),$customer->teamshas the new team;setAlertsandsetConnectorupdatepending, each team's rules and its connector, as in the other SDKs. Each access returns fresh read-only value objects (keep$customer->teamsin a variable if you read it twice). A helper that is given aCustomerfirst makes one cheap live read, the company's location list, and reads the whole layout again if the teams or Management differ from the object by id or active state; it takes group and rule ids from a live listing of each team it touches, never from the object; and it refuses (InvalidRequestError) aCustomerthat carries a location its company does not have. A company id makes the helper read the whole layout instead. The cost is in "How many requests": one request for the location list the object is checked against, and two per team whose group and rule ids the helper uses. ACustomeryou build yourself or restore from serialized form holds only the values it was given (the helpers still read live as above). - Checks first. Every helper checks all its arguments before it sends anything, sign-in included. Bad
input throws
InvalidRequestErrorwith no request made, so it costs no sign-in (sign-in is limited to 5 a minute); a value of the wrong type is refused by PHP's own types, also before any request. Call the SDK from files that declare strict types (declare(strict_types=1);): otherwise PHP converts numbers and booleans to strings, and strings to numbers and booleans, before the SDK sees them (123becomes the id"123","0"becomesfalse,"5"becomes the limit5), and the request is sent. The SDK still refuses what it can detect afterwards: an id that is"1"or empty (atrue) or a decimal such as"1.5"(a float). Surrounding whitespace in an id is refused, not trimmed.teams,userIdsandphrasestake any iterable and read it once. - Stops are reported. A helper that fails part-way throws
AccountErrorwith$step,$result(so far) and the cause ($cause, the same asgetPrevious()). Run it again with the same input to continue;changeLicenseandmoveUseralso recognise a person they left part-way. A connector that does not become active stopscreateCustomer,addTeamandsetConnectorat the end, once everything else is built:$stepis"connectors"and the cause isConnectorTimeoutErrororConnectorError(with$stateReason). - Existing people keep their license.
addBaseUser,addBaseManagerandaddIntegrationUserrefuse (InvalidRequestError, before any write) a person already set up with another license; usechangeLicense. - Alerts start switched off.
activateAlertsswitches them on for every team. A team does not need a manager: its alerts then show in the app only, and the result lists it. - Alert email is off for every person the helpers create, managers included. People switch it on in their own settings.
- Insights Hub "monitor all numbers" stays off. The helpers never switch it on and switch it off where they find it on.
- Cost on a large customer. Each helper reads the customer's layout once per call (three lists per team plus the locations), and the people of every team for the helpers that work on people. One
addBaseUseron a 10-team customer is 90 requests (see the request-count table); the cost grows with the number of teams and people. Run a batch of helpers in one process, one after another. - One process at a time per customer. Every list (lines, group membership, products) is read, merged and written back, so do not run helpers for the same customer from several processes at the same time: the later write would replace the earlier one.
- Invitations go last. People are created without one; it is emailed once their products,
groups and lines are in place (
invite: falseholds it back;sendInvitationssends it later). - Connectors.
new ConnectorSpec($type, $config, name: null, timeout: 600)(timeoutis how long the account helpers wait for the connector to settle; the client'sconnectorTimeoutis not used by them) takes the phone platform as the API names it and that platform's own settings;ConnectorSpec::netsapiens($apiUrl, $domain, $apiKey)is the shortcut for the documented one. Give the key in full each time: it is sent when a connector is created or repaired and is never kept, logged or shown. Any setting whose name contains key, secret, token, password, passwd, pwd, credential or auth is hidden at any depth invar_dump,print_r,var_export,json_encode, a string cast,serializeand exception messages and traces;$spec->config()returns the real values for sending. A new connector is checked every 10 seconds until it settles; its status is recorded on the team (connectorStatus,connectorStateReason). A re-run with a corrected key repairs a connector inerror; it never creates a second one.
| Helper | Does | Returns |
|---|---|---|
createCustomer($spec) |
Company with all three products, SSO domain claim (optional), first team and Management, connector on each (if given), groups, alerts (switched off), Insights Hub | Customer |
getCustomer($companyId) |
Reads the layout back; a layout it does not recognise is listed in pending |
Customer |
addTeam($customer, $team, $connector, alerts: null, reactivate: false) |
A further team with its connector, groups, alerts (copying the first team's phrases and levels unless alerts sets them) and Insights Hub |
Team |
setAlerts($customer, $alerts, team: null) |
Phrases and sentiment levels on one team or all; null keeps what is there; alerts keep their on or off state |
rule ids changed |
setConnector($customer, $connector, team: null) |
Attaches a phone system to the named team, or the first team and Management; refuses where an active one exists | list<Team> |
addBaseUser($customer, $person, $team, $line, invite: true) |
After Call, their line on the team's connector, First Alert and Insights Hub lists and the team's managers | Member |
addBaseManager($customer, $person, $teams, line: null, companyReports: false, invite: true) |
All three products on each team and Management, own line at Management, the teams' lines and groups; companyReports: true adds the company-wide reports group |
Member |
addIntegrationUser($customer, $person, invite: true) |
A data-reading user across every team: password sign-in, tagged department: "integration", every line |
Member |
changeLicense($customer, $userId, $to, teams: null, line: null) |
"base_manager" or "base_user", moving their own line between the team and Management |
Member |
moveUser($customer, $userId, $fromTeam, $toTeam) |
Moves a Base User's membership and line, or swaps one of a manager's teams; call history stays with the old team | Member |
changeLine($customer, $userId, $old, $new) |
A Base User's line: their mapping and the team's lists (a line another Base User still holds stays listed). A manager's own line at Management only | Member |
removeUser($customer, $userId, keepLines: false) |
Clears groups and lines, then deactivates; notes names teams left with no manager in an alert group (alerts are not changed) |
RemovalSummary (userId, license, releasedLines, deactivated, notes) |
activateAlerts($customer, team: null) |
Switches alerts on for every team. switchedOn (rule ids) and noManager (teams whose alert groups have no manager, so their alerts show in the app only) |
AlertActivation (switchedOn, noManager: NoManagerTeam with locationId, team, missing) |
sendInvitations($customer, userIds: null) |
Sends invitations not yet sent or expired; re-sends to userIds |
user ids |
listMembers($customer, license: null, team: null) |
Everyone, with license (base_user, base_manager, integration, other), teams and lines |
list<Member> |
licenseReport($customer) |
People by license and the number of teams (Management not counted) | LicenseReport (baseUser, baseManager, integration, other, teams, members) |
syncLines($customer, dryRun: false) |
Makes every line list match the people. Someone with After Call and one line who reads back as other keeps their line and is listed under other |
LineSyncReport (teams: TeamLines by location id with team, lines, other, firstAlert, insightsHub, holders; applied) |
offboardCustomer($customer, deactivateCompany: true) |
Pauses webhooks, stops every connector, deactivates integration users and the company | OffboardSummary (webhooksPaused, firstAlertWebhooksCleared, connectorsDeactivated, integrationUsersDeactivated, companyDeactivated) |
A Member lists every team the person is on after the call, not only the teams named in it. A line (extension or number) must be the whole value +?[0-9*#]{1,32}: "21 10" or "21-10" throws InvalidRequestError before any request.
Every helper that takes $customer also takes a company id. $team is a Team, its location id or
its name. Lines need an active connector (a connector that reports connected is running too): a
refused mapping throws AccountError whose cause is ExtensionMappingError, and no invitation is
sent. An extension belongs to one location only. A line another location already holds reaches you as
AccountError → ExtensionMappingError → ConflictError (message "Extension is already monitored at
another location.", $extensions lists the clashing lines):
try { $admin->accounts->addBaseUser($customer, $person, $team, '2101'); } catch (AccountError $err) { $clash = $err->find(ConflictError::class); // null when the stop had another cause if ($clash !== null) { echo 'already captured at another location: ', implode(', ', $clash->extensions), "\n"; } }
Companies, locations and people are never deleted; deactivate them. Connectors are stopped, not deleted.
Conversation layer: $ic->conversations (user login)
Sign in as the person. The platform decides what each call returns: a Base User gets their own calls, a Base Manager their teams'.
$me = new Client(email: getenv('IC_USER_EMAIL'), password: getenv('IC_USER_PASSWORD')); foreach ($me->conversations->calls() as $brief) { // today, newest first echo $brief, "\n"; // CallBrief(id='…', when='…'): no content } $history = $me->conversations->callerHistory('5555550142', limit: 5); $detail = $me->conversations->brief($callId); // summary, key points, tasks, sentiment, topics, alerts $tasks = $me->conversations->openTasks(); $myTeam = current(array_filter($me->conversations->teams(), fn ($t) => $t->kind === 'team')); // teams first, Management last $board = $me->conversations->teamView($myTeam); // for a manager: counts, alerts, open tasks, briefs
| Helper | Returns | Limits |
|---|---|---|
me(), teams() |
Who is signed in and the teams they can see: kind === 'team' first in name order, Management last (pick "my team" by kind). me()->lines is null: the API gives a user login no way to read its own lines |
|
calls(day:, since:, until:, team:, number:, search:, limit: 50) |
list<CallBrief>, newest first; default today |
window at most 31 days, limit at most 200 |
brief($callId) |
One CallBrief with key points, tasks, topics and the alerts it raised (read from one page of that day's alerts, so a day with more than 100 alerts can miss some) |
no transcript, no recording |
transcript($callId) |
The transcript of one call | one call per request |
recordingLink($callId) |
A RecordingLink that expires; the SDK never downloads the audio |
|
callerHistory($number, limit: 10) |
Recent briefs for one caller (last 31 days) | limit at most 50 |
openTasks(due:, team:) |
Open tasks with the id of the call each came from | up to 200 |
alerts(since:, until:, team:, limit: 50) |
list<AlertBrief> on this person's teams. status: throws InvalidRequestError and holder is null: the API has no alert status or holder yet |
as calls |
alert($alertId) |
One alert with its call brief | |
teamView($team, day:, since:, until:) |
Counts, alerts, open tasks and briefs for one team | as calls |
topics(since:, until:, team:) |
Topic volumes and rising topics (default last 7 days) | needs Insights Hub access |
reference($callOrAlert) |
The id and its page in the app, to pass to another system in place of content | |
parseFirstAlertEvent($payload) |
A FirstAlertEvent |
- Caller numbers are masked to their last four digits (
***0142) unless the client was created withmaskNumbers: false, also where a run of five or more digits appears in a name. Extensions are shown as they are. - Links:
CallBrief::$link,AlertBrief::$linkandreference()give the page in the app,<app>/after-call-copilot/calls/<id>or<app>/first-alert-copilot/alerts/<id>; they carry only an id of letters, digits,-and_(reference()refuses others, and a brief with another id haslinknull). <app>ishttps://app.intelligence.cloudunless you pass your own address:new Client(..., appUrl: 'https://...')(https only).- Limits are checked before any request (no sign-in either): a longer window, a larger limit,
numberwithsearch, an empty id, a team name that is empty,duethat is notYYYY-MM-DD, or a date without a time zone throwsInvalidRequestError.day:takesYYYY-MM-DD(or aDateTimeInterface); "today" andday:are midnight to midnight in PHP's default time zone (date_default_timezone_get()), with that date's own offset, daylight saving included.since:anduntil:take aDateTimeInterfaceor an RFC 3339 string with an offset. - Nothing is logged. The debug form (
var_dump,print_r) and string form of a brief show its id and time only. Keep summaries, names and numbers out of your own logs too. - An administrator login throws
WrongLoginError. There is no helper that walks every call; for a bounded daily job use$ic->intelligence->iterCalls. Weekly reports have no API endpoint, so there is no helper for them; webhook deliveries are unsigned, so there is nothing to verify.
Quick start: conversation intelligence
$intel = $user->intelligence; $intel->requireFrontline(); // One page of calls with a phone number in any format (partial digits match too). $page = $intel->searchCalls(phone: '+1 (555) 555-0142', dateFrom: new DateTimeImmutable('-30 days')); echo $page->total; foreach ($page as $call) { echo $call['call_date'], ' ', $call['sentiment_label'], ' ', $call['top_highlight'], "\n"; } // Every negative call this week, across all pages. foreach ($intel->iterCalls(sentiment: 'negative', dateFrom: new DateTimeImmutable('monday this week')) as $call) { // … } $call = $intel->getCall($callId); // summary, analysis, sentiment, tasks $lines = $intel->getTranscript($callId); // [{time, speaker: "Speaker 1", name, text}, …] $rec = $intel->getRecordingUrl($callId); // RecordingLink {url, expiresAt} or null $alerts = $intel->searchAlerts(alertName: 'Customer Threat', dateFrom: new DateTimeImmutable('-1 day')); $alert = $intel->getAlert($alertId, withCall: true); // the call under 'call' $tasks = $intel->listTasks(status: 'overdue', todayStart: '2026-11-02T00:00:00-06:00'); $dash = $intel->getInsightsDashboard(new DateTimeImmutable('-7 days'), new DateTimeImmutable());
Recordings
getRecordingUrl() returns only the link and its expiry. The link is a signed HTTPS URL to a WAV
file. Fetch it with no Authorization header; Range requests work. It is valid for 120 minutes,
so ask for a fresh one when you need it. Anyone holding it can download the audio: treat it as a
secret and never log it.
Calls and alerts as they happen
New calls arrive on the After Call webhook and alerts arrive on the First Alert webhook as they fire (see Webhooks). Don't poll the API for new data: read it when a person asks for something or when a webhook tells you to fetch details, and run scheduled jobs (exports, digests) at most once a day over a bounded date window.
Rules the SDK applies for you
- Filters: list methods accept only the filters the API supports. The API ignores unknown
parameters silently, so the SDK refuses them before sending (
InvalidRequestError;FilterErroris its old name and still catches it). Enums and ranges are checked; dates must be full timestamps;numberstakes up to 25 entries and strips formatting (a North American number is sent as its last 10 digits:+1 555-555-0142becomes5555550142);location_idlists take up to 50 ids. - Full-replacement writes (group members, a user's groups, locations and number mappings,
First Alert monitored numbers, Insights Hub numbers and groups, company and location products,
rule groups) have
add…/remove…/set…helpers that read, merge and write. The First Alert helpers always resend the webhook URL so it is not cleared;saveFirstAlertConfigrefuses a body withoutwebhook_url. - User create always sends an
Idempotency-Key, a new UUID unless you pass one, reused on retries. If the create returns 422 but left the user behind, the SDK finds the user by email and applieslocation_ids. - Connectors:
createConnectorandreactivateConnectorwait until the connector is running (activeorconnected),deactivateConnectorwaits forinactive, checking every 10 seconds for up to 10 minutes (connectorTimeouton the client sets the default for these low-level methods,$timeoutper call overrides it; account helpers use thetimeoutof theirConnectorSpec;wait: falsereturns at once).errorthrowsConnectorErrorwith$stateReason; no final status in time throwsConnectorTimeoutError. - Responses carry only the fields in the published reference. Anything else is dropped. The one-time sign-in link a user create can return is never passed through or logged.
- Test endpoints (connector dry run, webhook tests) report only success and the HTTP status.
- Retries: see Retries.
- Checks first: every helper of both layers checks its arguments before it signs in or sends
anything. Bad input throws
InvalidRequestErrorwith no request made. This holds for what reaches the SDK: a file withoutdeclare(strict_types=1)has its numbers and booleans converted by PHP first (see above).
Retries
One policy, the same in every SDK:
| Situation | What the client does |
|---|---|
| Network failure (no connection, timeout) or 5xx on a read, update, delete, or user create (which carries an idempotency key, reused on every try) | Retries up to maxRetries (3) times with exponential backoff and jitter: about 0.5, 1 and 2 seconds plus up to half again |
| Sign-in | Retried after a failure that provably never left (see the table below) and after a 5xx. A timeout or reset after the request was sent is not retried: it throws NetworkError with $requestSent true |
| Token renewal | The refresh token is sent again only after a 429 (the server did not use it) or after a network failure that provably never left this machine (see the table below). Any other outcome (a 5xx, a timeout after the request left, an unreadable answer) may have used it: it is never resent, and the client signs in instead. Sending a used refresh token ends every session of that login |
| Network failure or 5xx on any other create | Not retried: the error is thrown, so nothing is created twice |
429 with Retry-After within the limit (60 s; for sign-in, loginRateLimitWait, default 60 s) |
Waits Retry-After (backoff when absent), then retries; sign-in waits once |
429 with Retry-After above the limit |
Throws RateLimitError at once with $retryAfter set; it never waits first and then fails |
| 401 on a request | Renews the token once and retries |
Retry-After is read as a number of seconds; any other form counts as absent.
Connections for writes. A request that must not reach the server twice (sign-in, token renewal, and every
create without an idempotency key) is sent on a connection of its own: the SDK sets CURLOPT_FRESH_CONNECT and
CURLOPT_FORBID_REUSE for it. Without that, libcurl silently sends a request again on a new connection when a
reused keep-alive connection is reset before the answer, so the server could see the same refresh token or the
same create twice and the SDK would never know. The cost is a new connection (and a TLS handshake) per write;
reads, updates and deletes keep reusing connections. Another Guzzle handler than cURL's ignores these options.
Which failures never left. Guzzle and cURL report a failed transfer as an exception; the SDK reads
the cURL error number from the handler context (getHandlerContext()['errno']):
| Failure | cURL error | The request |
|---|---|---|
| Could not resolve the host | 6 (and 5, a bad proxy host) | never left |
| Could not connect: refused, unreachable | 7 | never left |
| TLS handshake or certificate check failed | 35, 51, 58, 60 | never left |
| Timeout before any connection was made (connect time 0) | 28 | never left |
| Timeout after connecting | 28 | may have left |
| Connection reset, nothing received, a write or read that failed | 56, 52, 55, ... | may have left |
| An answer that could not be decoded | 61, 23 | may have left (kind is decoding; not retried) |
| Any failure without a cURL number (another handler, a test double) | none | may have left: when unsure the SDK assumes it did |
NetworkError::$requestSent says which. Other Guzzle handlers than cURL's report no number, so every
failure through them counts as "may have left".
Bounds. One API request, including the sign-in or token renewal it needs and every retry and wait,
never runs past deadline (default 120 seconds). When the time left cannot cover the next wait,
the client stops at once: RateLimitError (with $retryAfter) after a 429, NetworkError with kind
"timeout" after network failures, or the last 5xx as an ApiError. Each attempt gets at most
timeout (30 s) or the time left, whichever is less, as Guzzle's timeout, and a fifth of it as
connect_timeout. Helpers that make many requests (createCustomer) apply the deadline to each request.
Connector settle waits are not counted: they have their own timeout (600 s). Inside a web request, pass
a smaller deadline (for example 10), loginRateLimitWait: 0 and maxRetries: 1.
Filters and paging
Low-level list methods take filters by their API names, exactly as in the reference:
$page = $admin->users->listCompanyUsers($companyId, ['status' => 'active', 'limit' => 100]); $next = $admin->users->listCompanyUsers($companyId, ['status' => 'active', 'limit' => 100, 'cursor' => $page->nextCursor]); foreach ($admin->users->iterCompanyUsers($companyId, ['status' => 'active']) as $user) { echo $user['email'], "\n"; }
A Page has items (records with the type/attributes wrapper removed), hasMore,
nextCursor, total, summary (call, alert and task totals for the whole filter) and raw. It is
iterable and countable. Every list method has an iter… twin that follows cursors 100 at a time.
Single reads and writes return the response body as documented; Client::unwrap($body) returns the
record inside.
Default windows: calls, alerts and topic calls start at 00:00 UTC seven days ago. Tasks have no
default window. The Insights Hub dashboard needs start and end.
Errors
An API error's text is HTTP <status> <code> (request_id <id>) plus text the SDK wrote itself; the
server's own message is never in it (it is on $e->serverMessage, which can contain numbers or
names: don't log it). Log status, code and request_id, not exception text or response bodies.
The error tree is the same in every SDK language:
IntelligenceCloudError
├─ ApiError ($status, $errorCode, $serverMessage, $requestId, $operationId)
│ ├─ AuthError (401: sign-in failed, or the token could not be renewed)
│ │ ├─ MfaRequiredError (the integration user's company has MFA on)
│ │ └─ PasswordExpiredError
│ ├─ NotFoundError (404: not found, or outside what this login can see)
│ ├─ ConflictError (409: duplicate, already active or inactive, extension held elsewhere; $extensions)
│ ├─ ValidationError (400, 422)
│ ├─ RateLimitError (429; $retryAfter in seconds)
│ └─ NetworkError (status 0; $kind transport | timeout | decoding; $requestSent; the HTTP library's exception is not attached)
├─ InvalidRequestError (bad input, refused before sending; FilterError is its old name)
├─ WrongLoginError (the other kind of login is needed; the message says which)
│ └─ FrontlineRequiredError (`$ic->intelligence` asked for conversation data with an admin login)
├─ ConnectorError (a connector ended in error; $stateReason)
│ └─ ConnectorTimeoutError (a new connector did not settle in time)
├─ ExtensionMappingError (numbers not mapped; $userId, $cause)
├─ AccountError (an account helper stopped part-way; $step, $result, $cause, find($class))
└─ WebhookPayloadError (a webhook body is not JSON or is malformed: answer 400)
└─ PayloadTooLargeError (over 256 KB: answer 413)
AccountError::find(ConflictError::class) returns the first error of that class in the cause chain: a
line another location holds arrives as AccountError → ExtensionMappingError → ConflictError.
InvalidRequestError is also thrown as FilterError (the 0.1.x name is an alias of the same class), so
existing catch (FilterError $e) blocks keep working.
use IntelligenceCloud\Exception\{ConflictError, NotFoundError, ValidationError}; try { $admin->users->setNumbers($companyId, $userId, $connectorId, ['2101']); } catch (ConflictError $e) { // Release $e->extensions at the other location first. } catch (ValidationError $e) { // e.g. the connector is not active yet } catch (NotFoundError $e) { // the user or connector is gone, or not yours }
Quote $e->requestId when you contact support.
Webhooks
Webhooks are how your integration hears about new calls and alerts: the After Call webhook for every call, the First Alert webhook for each alert as it fires. Subscribe to them; don't poll the API for new data.
Configure (admin)
The After Call webhook sends one event per call (type: end_of_call_summary) to one HTTPS URL per
location, for every call at the location.
$admin->intelligence->setAfterCallWebhook($locationId, 'https://hooks.example.com/ic/after-call/' . getenv('IC_WEBHOOK_TOKEN') . ''); $result = $admin->intelligence->testAfterCallWebhook($locationId); // WebhookTestResult {success, httpStatus}
There is no delete: pause with setAfterCallWebhook($locationId, $url, enabled: false).
The First Alert webhook is set in the location's First Alert configuration, keeping the monitored numbers (read-merge-write):
$admin->intelligence->setFirstAlertWebhook($locationId, 'https://hooks.example.com/ic/alerts/' . getenv('IC_ALERT_WEBHOOK_TOKEN') . ''); $result = $admin->intelligence->testFirstAlertWebhook($locationId); // WebhookTestResult {success, httpStatus}
Receive
- HTTPS, with a long, unguessable path token from the environment (
IC_WEBHOOK_TOKEN, at least 32 characters, one per location; make one withphp -r "echo bin2hex(random_bytes(32));"), compared in constant time (hash_equals). Deliveries are not signed, so the URL is the secret. Keep it out of logs: redact the path in your web server, proxy, load balancer and APM. The path is/ic/after-call/{token}for the After Call webhook and/ic/alerts/{token}for First Alert. - Answer 2xx within 2 seconds, then process asynchronously. Redirects count as failures. Delivery is tried 3 times, then dropped.
- Answer 2xx to event types you don't handle (
parseAfterCallEventreturns anUnknownEvent). Answer 400 only for a body that isn't a JSON object or is a malformed After Call event, 413 for one over 256 KB, and 404 for a wrong token. - Treat an event as a notification. Before you write anything from it into another system, read
$ic->intelligence->getCall($event->callId)with your user login; aNotFoundErrormeans drop the event. - Store by call id and upsert. The same call can arrive again (retries, calls with several legs), and
a repeated After Call event can carry newer data: it replaces the earlier one. Store each delivery
durably under
Deduplicator::upsertKey($event)(the call id) before acknowledging. Never drop a delivery because its call id was seen before. - Check, compare, store, remember.
$dedup->seen($event)only checks whether this exact delivery was remembered;$dedup->remember($event)records it and is called after your durable write. In order: parse → ifseen($event): answer 2xx → load what is stored underupsertKey($event)→ ifWebhooks::isOlder($event, $stored):remember($event)and answer 2xx without storing → else upsert →remember($event)→ answer 2xx.isOldertakes the stored event, its body or its timestamp, compares the events' owntimestampfields and is false when either has none. Ordering relies on the event's timestamp; when two deliveries carry the same timestamp, the later arrival wins. Without the comparison, a v1 that failed to store and is retried after v2 was stored would overwrite newer data with older. If the write fails, answer 5xx and do not remember: the sender's retry is then processed. An exact re-delivery is the same event type, location and call id with the same content (a SHA-256 of the canonical JSON of the parsed event, because the payload carries no version marker); a later delivery with newer data is not seen.seenandremembertake an event, a parsed body (array) or the raw body; a plain id throwsInvalidRequestError, because an id alone cannot tell newer data apart.Webhooks::deliveryKey()gives the key as text: the same key in every SDK language for the same event. - The default store is in memory and per process: with more than one worker or process it misses
deliveries the others remembered. Pass a shared store.
DedupStoreis two methods,has(string $key): boolandadd(string $key): void;PdoDedupStorekeeps the keys in a database table:
CREATE TABLE ic_webhook_deliveries ( id VARCHAR(512) PRIMARY KEY, -- the delivery key (over 400 characters: "sha256:<hex>") received_at VARCHAR(32) NOT NULL -- UTC, ISO 8601 );
$store = new PdoDedupStore($pdo, 'ic_webhook_deliveries'); $store->createTable(); // once, at deploy time (CREATE TABLE IF NOT EXISTS, as above) $dedup = new Deduplicator($store);
Without the table, has and add throw an error that names PdoDedupStore::createTable().
- To test locally, post the sample event:
curl -X POST http://localhost:8080/ic/after-call/$IC_WEBHOOK_TOKEN -H 'Content-Type: application/json' -d @examples/after-call-sample.json.
Plain PHP (examples/webhook_receiver.php):
use IntelligenceCloud\Exception\{PayloadTooLargeError, WebhookPayloadError}; use IntelligenceCloud\Webhook\{AfterCallEvent, Deduplicator, PdoDedupStore, Webhooks}; $token = (string) getenv('IC_WEBHOOK_TOKEN'); // at least 32 characters $path = (string) parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH); if (strlen($token) < 32 || !hash_equals('/ic/after-call/' . $token, $path)) { // constant time http_response_code(404); exit; } try { $event = Webhooks::parseAfterCallEvent((string) file_get_contents('php://input', false, null, 0, Webhooks::MAX_EVENT_BYTES + 1)); } catch (PayloadTooLargeError) { http_response_code(413); exit; } catch (WebhookPayloadError) { http_response_code(400); exit; } if (!$event instanceof AfterCallEvent || $event->isTest) { http_response_code(204); // another event type, or the test send exit; } $pdo = new PDO(getenv('IC_QUEUE_DSN')); $dedup = new Deduplicator(new PdoDedupStore($pdo, 'ic_webhook_deliveries')); // shared by every worker try { if ($dedup->seen($event)) { // an exact re-delivery we already stored http_response_code(204); exit; } $key = Deduplicator::upsertKey($event); $stored = loadCall($pdo, $key); // what you stored for this call (its timestamp), or null if ($stored !== null && Webhooks::isOlder($event, $stored['timestamp'])) { $dedup->remember($event); // an older delivery arriving late: keep the newer data http_response_code(204); exit; } upsertCall($pdo, $key, $event->timestamp, $event->raw); // your durable write, keyed on the call id $dedup->remember($event); // only after the write succeeded } catch (Throwable) { http_response_code(503); // not remembered: the sender's retry is processed exit; } http_response_code(204);
Laravel (examples/laravel/AfterCallWebhookController.php) follows the same order with a cache-backed
DedupStore and IcCall::updateOrCreate as the write.
AfterCallEvent has callId, locationId, timestamp, isTest, call, summary, location,
raw, and the read-only values callType, callerNumber, calleeNumber, durationSeconds,
summaryText and sentiment (properties; null when the event does not carry them).
Receive First Alert
The First Alert webhook posts the alert that fired: the alert id, the rule, the location, the call and the
time. The First Alert payload is not final yet. Webhooks::parseFirstAlertEvent (also
Conversations::parseFirstAlertEvent) returns a FirstAlertEvent: alertId (letters, digits, - and _,
at most 128 characters, kept as sent, under alert_id, else alert.id, else id; the first present
decides, and anything else, including a top-level alert_id that is not a string, is refused with
WebhookPayloadError), and rule, locationId, callId and timestamp when the delivery carries them in
the shapes known today; raw holds the whole payload. Take the alert id, answer 2xx at once, then fetch
the alert and its call with a login that is in every alert group (examples/first_alert_webhook_receiver.php):
$event = Webhooks::parseFirstAlertEvent($body); // WebhookPayloadError: answer 400 $dedup = new Deduplicator(new PdoDedupStore($pdo, 'ic_alert_deliveries')); try { if ($dedup->seen($event)) { http_response_code(204); exit; } storeAlertId($pdo, Deduplicator::upsertKey($event)); // durable $dedup->remember($event); // after the write } catch (Throwable) { http_response_code(503); exit; // not remembered: the retry is processed } http_response_code(204); fastcgi_finish_request(); // answer now, work afterwards (PHP-FPM) $alert = $user->intelligence->getAlert($event->alertId, withCall: true); // null when this login can't see it if ($alert !== null) { pageOnCallManager($alert['id'], $alert['call_id']); // ids only; never log the summary }
If your receiver was unavailable, read the window you missed once and skip alerts you have already handled. Alerts are dated by their call, so start the window 30 minutes before the receiver went down:
foreach ($user->intelligence->iterAlerts(dateFrom: $wentDown->modify('-30 minutes'), dateTo: $cameBack) as $alert) { if (!isset($handled[$alert['id']])) { // your own store of handled alert ids handleAlert($alert['id']); $handled[$alert['id']] = true; } }
Testing your code
IntelligenceCloud\Testing\FakeApi is a supported fake API: run your code and your CI with no account and
no network. It ships with the SDK (src/Testing, autoloaded) and needs no development dependency to load;
the example below uses PHPUnit only because it is a test. $api->client(role: 'admin' | 'user') returns a
real Client wired to the fake.
use IntelligenceCloud\Accounts\PersonSpec; use IntelligenceCloud\Exception\AccountError; use IntelligenceCloud\Exception\ValidationError; use IntelligenceCloud\Exception\WrongLoginError; use IntelligenceCloud\Testing\FakeApi; use PHPUnit\Framework\TestCase; final class MyIntegrationTest extends TestCase { public function testAddsABaseUser(): void { $api = new FakeApi(); $seeded = $api->seedCustomer(); // "Riverbend Auto Group", fictional $admin = $api->client(role: 'admin'); // a real IntelligenceCloud\Client $team = $seeded->customer->teams[0]; $sam = new PersonSpec('sam.ortiz@example.com', 'Sam', 'Ortiz'); $member = $admin->accounts->addBaseUser($seeded->customer, $sam, $team, '2109'); self::assertSame('base_user', $member->license); self::assertContains(['POST', "/companies/{$seeded->companyId}/users"], $api->writes); self::assertSame('2109', $api->faNumbers($team->locationId)[count($api->faNumbers($team->locationId)) - 1]); $start = count($api->requests); $admin->accounts->addBaseUser($seeded->customer, $sam, $team, '2109'); self::assertSame([], $api->writesSince($start)); // safe to run again } public function testReadsAPersonsDay(): void { $api = new FakeApi(); $ids = $api->seedCalls(3); // fictional calls, newest first $me = $api->client(role: 'user'); $briefs = $me->conversations->calls(); self::assertSame($ids, array_map(fn ($b) => $b->id, $briefs)); self::assertStringStartsWith('***', $briefs[0]->callerNumber); // numbers are masked self::assertSame(['Asked about an appointment'], $me->conversations->brief($ids[0])->keyPoints); $this->expectException(WrongLoginError::class); $api->client(role: 'admin')->conversations->calls(); } public function testResumesAfterAFailedWrite(): void { $api = new FakeApi(); $seeded = $api->seedCustomer(); $admin = $api->client(role: 'admin'); $team = $seeded->customer->teams[0]; $sam = new PersonSpec('sam.ortiz@example.com', 'Sam', 'Ortiz'); $api->failWrite(2); // the second write of the next call fails try { $admin->accounts->addBaseUser($seeded->customer, $sam, $team, '2109'); self::fail('expected a stop'); } catch (AccountError $e) { self::assertInstanceOf(ValidationError::class, $e->find(ValidationError::class)); $stopped = $e; } $again = $admin->accounts->addBaseUser($seeded->customer, $sam, $team, '2109'); // carries on self::assertSame($stopped->result->userId, $again->userId); } }
FakeApi |
Does |
|---|---|
new FakeApi(connectorOutcome: 'active', role: 'admin', strict: true) |
A new, empty fake |
client(role: null, asUser: null, ...$clientOptions) |
A real Client (role 'admin' or 'user'); other named arguments go to the Client constructor; waits do not sleep unless you pass sleeper; httpClient is refused. asUser (role 'user'): the id or email of a seeded person, so their calls, alerts, tasks and Insights Hub access follow their license and teams (a Base User sees only calls on their own lines, a manager their teams'; Insights Hub answers 403 without the product); clients for the same person share that login's sessions |
seedCustomer(teams: 1, people: true) |
Riverbend Auto Group through the account layer: teams, Management, two Base Users per team, one manager. Returns SeededCustomer (customer, baseUsers, managers, companyId, people: SeededPerson with userId, email, license, teams, lines; all read-only properties) |
seedCalls(n: 3, locationId: null, day: null, alerts: true, tasks: true, recording: false, topics: false) |
Fictional calls with details, tasks and alerts (555-01xx numbers), each reaching a seeded Base User's line in turn. recording: true adds a recording link (an example.com address that expires in two hours); topics: true fills topic volumes and rising topics. Returns the call ids, newest first |
$connectorOutcome |
'active', 'connected', 'error' or 'stuck' (never settles) for connection attempts made after it is set (a connector created or restarted later); it does not change connectors already waiting |
settleConnector($connectorOrLocation, $outcome = 'active') |
Settle connectors that are waiting: the one with this id, or every waiting one at this location ('active', 'connected' or 'error'); returns how many |
failNext(status: null, network: null, method: null, path: null, retryAfter: null, afterProcessing: false, signIn: null) |
The next matching request fails once: an HTTP status; network: 'connect' (never left), 'read_timeout', 'write_timeout', 'reused_timeout' or 'undecodable'; or the next sign-in answers signIn: 'mfa_required', 'password_expired' or 'invalid_credentials'. By default the failure comes before the platform acts; afterProcessing: true applies the request first and loses the answer. A renewal that fails with a network failure other than 'connect' has used its token |
failWrite(nth: 1, status: 400), networkDown(down: true), rateLimit(count: 1, retryAfter: 1), expireAccessTokens() |
Simpler knobs: the nth write fails; no network; 429s; every access token expires (the next call renews) |
$requests, $writes, $authLog (read-only properties), writesSince($start), count($method, $pathRegex), resetLog() |
The request log: every request the fake received, including those a knob answered, each FakeRequest with method, path, query, body, operation and answer (the HTTP status, or 'network:connect' and the like), so retries can be counted. Sign-in and renewal attempts are in $authLog: login, refresh, and refresh_reused when a used refresh token was sent again, which ends every session of that login, as on the platform |
products($uid, $lid), numbers($uid, $connectorId), faNumbers($lid), ihNumbers($lid), groupMembers($lid, $name) |
State to assert on |
httpHandler() |
The fake as a Guzzle handler, to send a request the SDK would refuse and see how the fake answers |
That table is the whole supported surface; everything else on FakeApi is private and may change.
Non-strict mode (strict: false) lets a connector type the spec does not list, an unknown query parameter and an unknown body field through; strict mode (strict: true) answers with the API's error shape when a request is not what the published
spec defines: an unknown path or method (404); an unknown query parameter, or a query value of the wrong type
(whole number, true/false), outside its enum or range, or not in its format (uuid, date-time) (400); a body
missing a required top-level field, carrying a top-level field the spec does not define, or with a top-level
value of the wrong JSON type, outside its enum or not in its format, including each item of a top-level list
(422). It does not check nested objects, rules that join several fields, or how the platform searches and
sorts, and it can only refuse what the spec states. Code that passes against it still needs one run against a
test company before release.
Running helpers from more than one process
Account helpers read, merge and write whole lists. Two processes changing the same customer at once can each
read the old list and write back their own version, and one change is lost; two runs of createCustomer for a
new customer can create it twice. Run at most one account helper per customer at a time. On one machine, a
file lock is enough:
function withCustomerLock(string $companyId, callable $fn): mixed { $fh = fopen(sys_get_temp_dir() . '/ic-customer-' . hash('sha256', $companyId) . '.lock', 'c'); flock($fh, LOCK_EX); // waits for any other process on this machine try { return $fn(); } finally { flock($fh, LOCK_UN); fclose($fh); } } withCustomerLock($companyId, fn () => $admin->accounts->addBaseUser($companyId, $person, $team, '2101'));
Across several machines, use a lock row in your database. Keep a table with one row per customer, for example
customer_locks(company_id PRIMARY KEY); insert the row if it is missing, then select it for update inside a
transaction that wraps the helper call. A second process waits at the SELECT ... FOR UPDATE until the first
commits or rolls back:
function withCustomerLockRow(PDO $pdo, string $companyId, callable $fn): mixed { $pdo->beginTransaction(); try { // insert-if-missing, in your database's own syntax (a duplicate key is fine) try { $pdo->prepare('INSERT INTO customer_locks (company_id) VALUES (?)')->execute([$companyId]); } catch (PDOException) { // the row exists } $pdo->prepare('SELECT company_id FROM customer_locks WHERE company_id = ? FOR UPDATE')->execute([$companyId]); $result = $fn(); // the row stays locked until the transaction ends $pdo->commit(); return $result; } catch (Throwable $e) { $pdo->rollBack(); throw $e; } }
Run the insert as its own short statement, committed before the locking transaction, if your database aborts a
transaction after a failed statement. For a new customer, lock on a
key you already have (your own account id) until createCustomer returns and you have stored companyId.
How many requests
Measured against IntelligenceCloud\Testing\FakeApi with a fresh client (one GET /me included, sign-in not
counted); tests/Unit/RequestCountsTest.php pins these numbers.
The published limits are 5 requests a second per user, bursts of 20, and 50,000 a day per company.
| Helper | 1-team customer | 10-team customer |
|---|---|---|
createCustomer (first run, one team) |
34 | 34 |
addTeam (the 2nd team; the 10th team) |
n/a | 23; 23 |
createCustomer, re-run |
18 | 18 |
addBaseUser (customer passed as a company id) |
36 | 90 |
addBaseManager (on every team) |
32 | 158 |
activateAlerts (customer passed as an object; as a company id), rules off before the call |
15; 21 | 105; 120 |
setAlerts (both phrase alerts, Customer object) |
8 | 62 |
syncLines (object; company id) |
11; 19 | 65; 100 |
licenseReport (object; company id) |
8; 16 | 35; 70 |
calls (one page) |
2 | 2 |
brief |
3 | 3 |
A helper given a company id reads the whole layout first (for a 1-team customer 9 requests: the company, its locations, and each location's groups, rules and connectors, plus the domains); given a Customer object it reads only the location list it checks the object against (1 request), plus the groups and rules of each team whose ids it uses (2 per team), so passing the object saves 8 requests on a 1-team customer and 35 on a 10-team one for syncLines and licenseReport. Worked total: setting up a ten-team customer end to end with a Customer object (create, nine addTeam, both phrase alerts, one manager per team, three Base Users per team, activate) takes 2,497 requests, about 8.3 minutes at 5 requests a second (tests/Unit/RequestCountsTest.php pins it).
The counts assume a freshly seeded customer with two Base Users per team and one manager, alert rules off before activateAlerts, a connector that settles at its first check, and the customer passed as an object to addTeam. Each further 10 seconds a new connector takes to settle adds one request per connector (one status check). At 5 a second a 10-team addBaseManager takes about 30 seconds; the client's retries absorb short 429 bursts.
Upgrading from 0.2
- Connectors in account helpers: a connector that does not settle, or ends in error, arrives as
AccountError(step"connectors") whose cause isConnectorTimeoutErrororConnectorError, once everything else is built. A 0.2-stylecatch (ConnectorTimeoutError)aroundaddTeamno longer catches it:
try { $admin->accounts->addTeam($customer, $team, $connector); } catch (AccountError $err) { if ($err->find(ConnectorTimeoutError::class) !== null) { // still settling: run addTeam again later // ... } elseif ($err->find(ConnectorError::class) !== null) { // ended in error: check stateReason, fix the key, run again // ... } }
The settle timeout is ConnectorSpec::$timeout (600 s). The client's connectorTimeout and the $timeout argument of the low-level connectors->createConnector(), reactivateConnector() and deactivateConnector() apply only to those methods.
Deduplicator::isDuplicate()is gone:seen($event)checks,remember($event)records after your write (see "Receive").- Account results are typed (
AlertActivation,LicenseReport,LineSyncReport,RemovalSummary,OffboardSummary). CHANGELOG.mdlists every breaking change.
Method list
Every API operation is a method named after its operationId, grouped by reference section. Path
ids come first, then the request body as an array with the field names from the reference, then
filters as an array.
| Namespace | Methods |
|---|---|
$ic->resellers |
getResellerBranding, updateResellerBranding, getResellerSmtpSettings, saveResellerSmtpSettings, deleteResellerSmtpSettings |
$ic->companies |
listCompanies / iterCompanies, createCompany, getCompaniesMfaSummary, getCompany, updateCompany, deactivateCompany, reactivateCompany, getCompanyBranding, updateCompanyBranding; helpers addProducts, removeProducts, findCompanies, findCompany |
$ic->sso |
listCompanyDomains, claimCompanyDomain, removeCompanyDomain, listDomainVerifications, verifyDomain, getIdentityProvider, connectIdentityProvider, disconnectIdentityProvider, testIdentityProvider |
$ic->products |
listProducts, listCompanyProducts, listUserProducts, enableUserProduct, disableUserProduct |
$ic->locations |
listVerticals, listCompanyLocations / iterCompanyLocations, createLocation, getLocation, updateLocation, deactivateLocation, reactivateLocation; helpers addProducts, removeProducts, findLocation |
$ic->groups |
listUserGroups / iterUserGroups, createUserGroup, getUserGroup, updateUserGroup, deleteUserGroup, getUserGroupMembership, setUserGroupMembership; helpers addMembers, removeMembers, addUserToGroups, removeUserFromGroups, userGroupIds, findGroup |
$ic->connectors |
listConnectorTypes, testConnector, listLocationConnectors / iterLocationConnectors, createConnector, getConnector, updateConnector, deactivateConnector, reactivateConnector, listCompanyConnectors / iterCompanyConnectors; helpers waitForStatus, findConnector |
$ic->firstAlert |
listAlertRules / iterAlertRules, createAlertRule, getAlertRule, updateAlertRule, deleteAlertRule, duplicateAlertRule, getFirstAlertConfig, saveFirstAlertConfig, testFirstAlertWebhook, getAlertNotificationPreferences, setAlertEmailPreferences, setAlertDigestPreferences; helpers addMonitoredNumbers, removeMonitoredNumbers, setMonitoredNumbers, addRuleGroups, removeRuleGroups, findRule |
$ic->insightsHub |
getInsightsHubSetup, saveInsightsHubSetup, updateInsightsHubSetup, getInsightsHubConfig, updateInsightsHubConfig, getUserInsightsHubAccess; helpers addNumbers, removeNumbers, setNumbers, addGroups, removeGroups |
$ic->users |
listCompanyUsers / iterCompanyUsers, createCompanyUser, getCompanyUser, updateCompanyUser, deactivateCompanyUser, reactivateCompanyUser, resendInvitation, resetPassword, getUserNumberMappings, setUserNumberMappings, listLocationUsers / iterLocationUsers, getLocationUser; helpers findUserByEmail, addLocations, removeLocations, userNumbers, addNumbers, removeNumbers, setNumbers |
$ic->afterCallSettings |
getUserAfterCallSettings, updateUserAfterCallSettings |
$ic->account |
getMe, listVisibleLocations / iterVisibleLocations |
$ic->calls |
listCalls / iterCalls, getCall, getCallTranscript |
$ic->alerts |
listAlerts / iterAlerts, getAlertsDashboard |
$ic->tasks |
listTasks / iterTasks |
$ic->insights |
getInsightsDashboard, listTopicCalls / iterTopicCalls |
$ic->webhooks |
getAfterCallWebhook, saveAfterCallWebhook, testAfterCallWebhook |
$ic->intelligence |
whoami, requireFrontline, searchCalls / iterCalls, getCall, getTranscript, getRecordingUrl, searchAlerts / iterAlerts, getAlert($alertId, withCall: false), getAlertsDashboard, listTasks / iterTasks, getInsightsDashboard, listTopicCalls / iterTopicCalls, getAfterCallWebhook, setAfterCallWebhook, testAfterCallWebhook, getFirstAlertWebhook, setFirstAlertWebhook, testFirstAlertWebhook |
$ic->accounts |
see Account layer: createCustomer, getCustomer, addTeam, setAlerts, setConnector, addBaseUser, addBaseManager, addIntegrationUser, changeLicense, moveUser, changeLine, removeUser, activateAlerts, sendInvitations, listMembers, licenseReport, syncLines, offboardCustomer |
$ic->conversations |
see Conversation layer: me, teams, calls, brief, transcript, recordingLink, callerHistory, openTasks, alerts, alert, teamView, topics, reference, parseFirstAlertEvent |
$ic |
login, logout, close, call($operationId, $path, $query, $body), Client::unwrap($body) |
Also: Webhooks::parseAfterCallEvent, Webhooks::parseFirstAlertEvent, Webhooks::upsertKey, Webhooks::deliveryKey, IntelligenceCloud\\Testing\\FakeApi, FirstAlertEvent, UnknownEvent, Deduplicator, DedupStore,
InMemoryDedupStore, PdoDedupStore, Page, the error classes, and the account-layer value objects in
IntelligenceCloud\Accounts (CustomerSpec, TeamSpec, ConnectorSpec, PersonSpec, AlertSetting,
AlertSettings, Customer, Team, Member, …) and the conversation-layer ones in
IntelligenceCloud\Conversations (CallBrief, AlertBrief, TaskBrief, Reference, …).
The $ic->intelligence search helpers take named arguments:
searchCalls(phone:, text:, dateFrom:, dateTo:, status:, sentiment:, hasOpenTasks:, multiLeg:, locationIds:, companyId:, limit:, cursor:)
and searchAlerts(alertName:, numbers:, text:, sentiment:, dateFrom:, dateTo:, locationIds:, topic:, companyId:, limit:, cursor:).
phone and text both map to the API's one search field: pass one or the other.
Examples
| File | What |
|---|---|
examples/create_customer.php |
Create a customer, add a Base User and a Base Manager, switch the alerts on (dry run unless --apply) |
examples/manage_people.php |
Change a license, move a person, change a line, remove a person, check the lines |
examples/my_day.php |
A person's day: today's call briefs, open tasks and alerts, with masked numbers and no content in logs |
examples/search_calls.php |
Calls, transcript, recording link (prints counts and ids only) |
examples/webhook_receiver.php |
Plain PHP After Call receiver: parse, seen, upsert by call id, remember; 5xx on a storage failure |
examples/first_alert_webhook_receiver.php |
Plain PHP First Alert receiver that fetches each alert and its call |
examples/laravel/AfterCallWebhookController.php |
Laravel receiver |
examples/nightly_catch_up.php |
Once-a-day catch-up over the last 48 hours |
examples/after-call-sample.json |
A sample After Call event to post to your receiver locally |
Administrator examples read IC_ADMIN_EMAIL and IC_ADMIN_PASSWORD; the others, which sign in as a person,
read IC_USER_EMAIL and IC_USER_PASSWORD. The receivers read IC_WEBHOOK_TOKEN /
IC_ALERT_WEBHOOK_TOKEN (at least 32 characters) and IC_QUEUE_DSN (a PDO DSN for the shared store). Each
example uses the fictional customer Riverbend Auto Group.
License
Intelligence Cloud SDK Licence. Copyright (c) 2026 Creo Solutions, Inc. d/b/a Tresic. Partners, their customers and contractors working for either may use, copy, modify and distribute the SDK solely to access Intelligence Cloud. Use of the API is governed by the Intelligence Cloud API and SDK Terms (https://docs.intelligence.cloud/terms/api) and your agreement with Tresic or your provider. Provided as is. See LICENSE.