Orders, payments, refunds and sign-ups should be recorded on your server, where they cannot be blocked or faked. The five server SDKs wrap POST /api/v1/track with the same methods and the same behaviour in every language. The log-style POST /api/v1/server/events is a different endpoint and is not used by these SDKs; see Server events.
Shared behaviour
Key and endpoint
Create a key on ConsoleConfigurationSettingsAPI keys with the Server track scope. The key starts with wck_ and is shown once; keep it in server configuration, never in a repository, a browser or an app. The ingest address is built into the SDKs, so leave the endpoint option unset; set it only when TapCub gives you a dedicated address, such as for a private deployment.
Methods
| Method | What it records |
|---|---|
track | A business event, optionally with a login ID, device ID, session ID, idempotency key, time, account and request context |
trackSignup | sign_up; links the anonymous device to the new login ID. invitedBy becomes $invited_by |
bind / unbind | Add or remove identities (email, mobile, unionid, openid, custom). Email and mobile are SHA-256 hashed in the SDK |
profileSet / profileSetOnce / profileIncrement / profileAppend / profileUnset | User profile properties. $name, $email, $phone and $avatar are display fields |
itemSet / itemDelete | Dimension rows such as products, articles and stores |
trackUpdate / trackOverwrite | Merge into or replace the properties of the stored event with the same insertId |
groupSet | Account traits for type:id; events join an account with the group option |
flush / close | Send the queue now / stop and send the rest |
Python uses snake_case (track_signup, profile_set), Go uses exported names (TrackSignup). Field rules are in SDK overview.
Sending modes
| Mode | Behaviour |
|---|---|
| batch | Default except PHP. Events are queued in memory and sent every 3 seconds or when 200 are queued, at most 1000 events and 1 MB per request. Up to 10,000 events wait in memory; beyond that the oldest are dropped and reported as QUEUE_FULL |
| sync | Default for PHP. Every call sends at once and raises on failure |
| debug | Like sync, against ?debug=1: the server validates and answers per event, nothing is stored. Use it while integrating |
Network errors, 5xx and 429 are retried up to 5 times with exponential backoff (0.5 s doubling, at most 30 s) and Retry-After. The batch is resent unchanged. Other 4xx responses are not retried. In batch mode, failures that are given up and events the server rejects inside a successful response go to the error callback; flush and close raise the first one instead.
Idempotency
The SDKs do not generate insertId. For events that must not be counted twice, pass a natural key of at most 36 characters, such as the order or payment ID, and keep it when your own code retries. The server keeps one event per insertId.
Cleaning before send
The server rejects the whole request if one event breaks its schema, so each SDK cleans every event before queueing it: strings over 1000 characters are cut, nested objects become JSON strings, a list of objects such as items stays one level deep, unknown context fields and invalid values are dropped. IDs are never cut: an ID that is too long, an unknown login type or a malformed account key is an argument error and nothing is queued. All five SDKs pass the same conformance vectors (packages/shared/test-vectors/track in the SDK repository).
Where a sign-up came from
The website script knows the visit source; tapcub.getAttribution() returns it. Send that object to your backend with the sign-up form and pass it unchanged as context.campaign, together with the request's ip and user_agent, which let TapCub infer the source when there is no cookie. The examples below show this for each language.
Errors
| Code | Meaning |
|---|---|
NO_API_KEY / BAD_API_KEY | 401: the key is missing, invalid, expired or lacks Server track |
VALIDATION | 400: the body does not match the field rules (the message lists the first issues) |
HTTP_<status> | Another failed status |
NETWORK | No response after all retries |
EVENT_REJECTED | The request was accepted but some events were not, for example a profile operation for an unknown user; per-event warnings are attached |
QUEUE_FULL | The memory queue overflowed and the oldest events were dropped |
Every error carries the events that were not stored. A successful send still only means the server accepted the event; check the event list for the first events. See Server events & log import.
Node.js
Node.js 18 or newer, no dependencies, ESM and CommonJS with types.
Install
npm install @tapcub/nodeInitialize
import { TapCub } from '@tapcub/node';
const tc = new TapCub({
apiKey: process.env.TAPCUB_API_KEY,
onError: (err) => console.warn(err.code, err.message),
});Options: endpoint, consumer ('batch' / 'sync' / 'debug'), maxBatch, flushIntervalMs, maxQueueSize, maxRetries, timeoutMs, gzip, onError, logger, fetch.
Events
tc.track('purchase', {
loginId: user.id,
insertId: order.id,
properties: { revenue: 19.9, currency: 'USD', items: [{ item_id: 'sku-1', price: 19.9, quantity: 1 }] },
});Methods return a promise; in batch mode it resolves at once. Argument errors throw a TypeError.
Identity
tc.trackSignup(user.id, {
deviceId: req.body.tapcubDeviceId,
invitedBy: req.body.inviterId,
context: { campaign: req.body.attribution, ip: req.ip, user_agent: req.get('user-agent') },
});
tc.profileSet(user.id, { plan: 'pro', $name: user.name });
tc.bind(user.id, { email: user.email });Shutdown
Call await tc.close() on SIGTERM; the client also flushes on beforeExit. In serverless functions await tc.flush() before returning, or use consumer: 'sync'.
PHP
PHP 8.0 or newer with ext-curl and ext-json.
Install
composer require tapcub/tapcub-phpInitialize
use TapCub\TapCub;
$tc = new TapCub(getenv('TAPCUB_API_KEY'));The second argument is the endpoint (null for the default). The third is options: consumer ('sync' / 'batch' / 'debug'), maxBatch, maxQueueSize, maxRetries, timeout, gzip, onError, logger (PSR-3 style).
Events
$tc->track('purchase', [
'loginId' => $user->id,
'insertId' => $order->id,
'properties' => ['revenue' => 19.9, 'currency' => 'USD', 'items' => [['item_id' => 'sku-1', 'price' => 19.9, 'quantity' => 1]]],
]);In sync mode each call returns the server response and throws TapCubException on failure (getErrorCode(), getStatus(), getEvents()). Argument errors throw InvalidArgumentException. Empty and numeric-keyed arrays are always sent as JSON objects.
Identity
$tc->trackSignup((string) $user->id, [
'deviceId' => $request->input('tapcubDeviceId'),
'invitedBy' => $request->input('inviterId'),
'context' => ['campaign' => $request->input('attribution'), 'ip' => $request->ip(), 'user_agent' => $request->userAgent()],
]);
$tc->profileSet((string) $user->id, ['plan' => 'pro', '$name' => $user->name]);Batching
With 'consumer' => 'batch' events are sent when 200 are queued, on flush() / close(), when the client is destroyed, or at the end of the request. Failures at that point go to onError. In queue workers and long-running servers (Octane, RoadRunner, Swoole) call flush() after each job.
Python
Python 3.8 or newer, standard library only, typed.
Install
pip install tapcubInitialize
from tapcub import TapCub
tc = TapCub(os.environ["TAPCUB_API_KEY"], on_error=lambda e: log.warning("%s %s", e.code, e))Keyword options: consumer ("batch" / "sync" / "debug"), max_batch, flush_interval (seconds), max_queue_size, max_retries, timeout, gzip, on_error, logger. Batch mode sends from a daemon thread and flushes when the interpreter exits.
Events
tc.track(
"purchase",
login_id=user.id,
insert_id=order.id,
properties={"revenue": 19.9, "currency": "USD", "items": [{"item_id": "sku-1", "price": 19.9, "quantity": 1}]},
)time takes milliseconds or a datetime. Argument errors raise ValueError; send failures raise TapCubError in sync mode.
Identity
tc.track_signup(
user.id,
device_id=data.get("tapcubDeviceId"),
invited_by=data.get("inviterId"),
context={"campaign": data.get("attribution"), "ip": request.META.get("REMOTE_ADDR"), "user_agent": request.headers.get("User-Agent")},
)
tc.profile_set(user.id, {"plan": "pro", "$name": user.name})Workers
Scripts, Lambda handlers and Celery tasks should call tc.flush() before returning. With pre-forking servers (gunicorn --preload, uWSGI) create the client after the fork; the sender thread does not survive it.
Java
Java 11 or newer, no runtime dependencies.
Install
<dependency>
<groupId>com.tapcub</groupId>
<artifactId>tapcub-java</artifactId>
<version>0.1.0</version>
</dependency>Gradle: implementation("com.tapcub:tapcub-java:0.1.0").
Initialize
import com.tapcub.server.TapCub;
TapCub tc = TapCub.builder(System.getenv("TAPCUB_API_KEY"))
.onError(e -> log.warn("tapcub {} {}", e.getCode(), e.getMessage()))
.build();Builder options: endpoint, mode (BATCH / SYNC / DEBUG), maxBatch, flushInterval, maxQueueSize, maxRetries, timeout, gzip, flushOnShutdown, onError, logger, httpClient. The client is thread-safe and AutoCloseable; in Spring Boot declare it as a bean with destroyMethod = "close".
Events
tc.track("purchase", new TrackOptions()
.loginId(user.getId())
.insertId(order.getId())
.property("revenue", 19.9)
.property("items", List.of(Map.of("item_id", "sku-1", "price", 19.9, "quantity", 1))));Argument errors throw IllegalArgumentException; send failures throw TapCubException in sync mode.
Identity
tc.trackSignup(user.getId(), new SignupOptions()
.deviceId(form.getTapcubDeviceId())
.invitedBy(form.getInviterId())
.context(Map.of("campaign", form.getAttribution(), "ip", req.getRemoteAddr(), "user_agent", req.getHeader("User-Agent"))));
tc.profileSet(user.getId(), Map.of("plan", "pro", "$name", user.getName()));Campaign builds the campaign object field by field when you do not have the browser's map.
Go
Go 1.21 or newer, standard library only.
Install
go get github.com/tapcub/tapcub-goInitialize
tc, err := tapcub.New(os.Getenv("TAPCUB_API_KEY"), tapcub.Config{
OnError: func(err error) { log.Println(err) },
})
if err != nil {
log.Fatal(err)
}
defer tc.Close()tapcub.Config fields: Endpoint, Consumer (ConsumerBatch / ConsumerSync / ConsumerDebug), MaxBatch, FlushInterval, MaxQueueSize, MaxRetries, Timeout, Gzip, OnError, Logger, HTTPClient. The zero value is valid.
Events
err := tc.Track("purchase", &tapcub.TrackOptions{
LoginID: user.ID,
InsertID: order.ID,
Properties: tapcub.Properties{"revenue": 19.9, "items": []tapcub.Properties{{"item_id": "sku-1", "price": 19.9, "quantity": 1}}},
})Argument errors wrap tapcub.ErrInvalidArgument; send errors are *tapcub.Error (Code, Status, Events).
Identity
err := tc.TrackSignup(user.ID, &tapcub.SignupOptions{
DeviceID: form.DeviceID,
InvitedBy: form.InviterID,
Context: &tapcub.Context{Campaign: form.Attribution, IP: clientIP(r), UserAgent: r.UserAgent()},
})
_ = tc.ProfileSet(user.ID, tapcub.Properties{"plan": "pro", "$name": user.Name})The browser's attribution JSON unmarshals straight into *tapcub.Campaign.