Skip to main content
Requires PHP 8.2 or later and cURL, unless you provide an HTTP transport.

Configure the client

Use one authentication method: oauthClientCredentials, a callable tokenProvider, or a static accessToken. OAuth credentials support optional tokenUrl, scope, audience and additionalParameters. A token provider receives forceRefresh and reason, returning a token string or an array with accessToken, optional expiresAt (epoch milliseconds) or expiresInSeconds. Refreshable authentication caches tokens and retries one 401 after refresh. Keep credentials in server configuration. For long-lived Laravel workers, send request and session IDs per event so one client’s defaults do not mix visitors.
Read data or recommendations for the single-call result items, and preserve request_id. For auto sections, pass next_cursor to the next call and stop at done or when the cursor is absent.

Several rails

Batch options include userId or anonymousId, sessionId, requestId and a non-empty sets array. Set fields are key, contextId, limit, itemId, cartItemIds, pageType, filters, scope, query. Keys must be unique and match [A-Za-z0-9_.:-]{1,64}. NeuronSDK::MAX_RECOMMENDATION_SETS_PER_BATCH is 8. Larger explicit batches are split. Each rail has its own status, optional error and attribution request_id. An explicit batch request ID covers the first chunk only; later chunks receive separate IDs.

Events and PendingResult

trackEvent(array $data) buffers one occurrence and returns PendingResult. Use integer event and item IDs, not names. Optional fields include contextId, occurredAt (Unix seconds), requestId, sessionId, metadata, query and a stable deduplicationId for retries. trackSearch(array $data) accepts userId, a non-empty query, optional resultItemIds, eventId and attribution fields. It records a search without an item. createEvent(array $data) is an alias of trackEvent, not an event-type creation API. flushEvents(array $options = []) sends the pending buffer. PHP has no SDK background flush timer: flush explicitly in workers and short-lived handlers. The SDK also attempts a shutdown flush, which is not a durable delivery guarantee. To batch, enqueue multiple events before flushing and waiting. Waiting immediately for each event sends them sequentially. Automatic attribution uses only the latest single-list/search call; always pass each rail’s ID when displaying several rails.

Items

Set metadata.source_item_id to your stable source identifier to update the same item on repeated ingestion. Other arbitrary metadata fields do not enable this matching. Store NSL’s generated ID for events and direct patchItem updates. PHP does not expose a separate createItem method.

Client state

setAccessToken(string $token) replaces refreshable authentication with a static token. setBaseUrl(string $url) and setTimeout(int $timeoutMs) change connection settings. setRequestId(?string $id) / getRequestId() manage default attribution; setSessionId(?string $id) / getSessionId() manage the instance session. With automatic sessions enabled, a missing session may be regenerated.

Errors and logging

Catch NeuronSearchLab\SDKAuthError for token acquisition, SDKHttpError for HTTP failures (status, statusText, body), and SDKTimeoutError for timeouts (timeoutMs). Invalid arguments may throw InvalidArgumentException. Retry transient failures with bounded backoff; correct validation and permission errors before retrying.
configureLogger configures the shared logger, also available through SDKLogger::instance(). Configuration accepts level, enableNetworkBodyLogging, enablePerformanceLogging, transport and redactKeys. The default level is INFO; payload and performance logging are off. Levels run from TRACE, DEBUG, INFO, WARN, ERROR to FATAL. Logger methods are configure, trace, debug, info, warn, error, fatal, shouldLog, canLogNetworkPayloads and isPerformanceLoggingEnabled. Logging methods take a message and optional context array. Keep user payloads and credentials out of production logs.

Custom authentication and transport

httpClient($url, $init) provides the request transport. Return an array with integer status, string statusText, an array of headers, and a string body containing the response. Use this when cURL is unavailable or for controlled tests. backoffStrategy($attempt) returns a retry delay in milliseconds. For custom token acquisition, use the supported tokenProvider configuration rather than constructing authentication internals. See Authentication and the Core API for the wire contract.
This reference targets PHP 2.3.0. To use context groups, pass their member context IDs as explicit sets in one batch. Group rules apply automatically. This published client version does not expose a groupId helper.