clikgate / clikgate-laravel
Laravel integration for the Clikgate server SDK: auto-discovered provider, Clikgate facade, click-ID middleware and queued goal sending.
Requires
- php: >=8.2
- clikgate/clikgate-php: ^2.1.1
- illuminate/contracts: ^12.0 || ^13.0
- illuminate/http: ^12.0 || ^13.0
- illuminate/queue: ^12.0 || ^13.0
- illuminate/support: ^12.0 || ^13.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.95
- orchestra/testbench: ^10.0 || ^11.0
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^10.5 || ^11.5 || ^12.4 || ^13.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Laravel integration for clikgate/clikgate-php: an auto-discovered service provider, the Clikgate facade, the clikgate middleware, $request->clikgateClickId(), $request->clikgateInstallation(), and queued goal sending. Laravel 12 and 13.
composer require clikgate/clikgate-laravel
Set CLIKGATE_API_KEY=cg_live_… (or cg_test_…) in .env. To change other settings, publish the config with php artisan vendor:publish --tag=clikgate-config.
use Clikgate\Laravel\Facades\Clikgate; Clikgate::goal('account_opened', ['clickId' => $application->click_id, 'reference' => $application->reference, 'value' => '2000000']);
End to end
One flow with the typed methods only.
use Clikgate\Enum\EventType; use Clikgate\Enum\Provider; use Clikgate\Laravel\Facades\Clikgate; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; // 1. Sign-in: after YOUR own sign-in check. The customer ID is the signed-in user's ID, never read from the request. Route::post('/login', function (Request $request) { if (!Auth::attempt($request->only('email', 'password'))) { abort(401); } $user = Auth::user(); $customerId = (string) $user->id; // Path B: the app's Clikgate-Installation header, no secret (null when missing or invalid: skip the call) if (null !== $installation = $request->clikgateInstallation()) { Clikgate::identifyUser(['installation' => $installation, 'customerId' => $customerId]); } // Path A: an identity token the app passes to the mobile SDK; 4. and the user's referral code and link $referrer = Clikgate::referrals()->getOrCreateReferrer('rpg_01J…', ['customerId' => $customerId, 'displayName' => $user->name]); return ['user' => $user, 'clikgateIdentityToken' => Clikgate::createIdentityToken($customerId, ['customerSince' => $user->created_at]), 'referralCode' => $referrer->code, 'referralUrl' => $referrer->url]; }); // 2. Goals (queued with CLIKGATE_QUEUE) and 3. payments, right after your own verification with the gateway Clikgate::goal('account_opened', ['clickId' => $request->clikgateClickId(), 'reference' => 'APP-55231', 'isFirst' => true]); Clikgate::payments()->confirm(['provider' => Provider::Paystack, 'reference' => 'T123456', 'status' => 'success', 'amount' => '7500', 'currency' => 'NGN', 'goal' => 'order_paid']); // 5. Webhooks: the raw body, then the typed object Route::post('/webhooks/clikgate', function (Request $request) { // config/services.php: 'clikgate' => ['webhook_secret' => env('CLIKGATE_WEBHOOK_SECRET')] (the secret from Developers › Webhooks) $event = Clikgate::verifyWebhook($request->getContent(), $request->header('Clikgate-Signature'), (string) config('services.clikgate.webhook_secret')); $referral = $event->asReferral(); // null for other event types if (null !== $referral && EventType::ReferralQualified === $event->type) { // Clikgate never pays rewards: grant yours, once per $event->id grantReward($referral->referrer->customerId, $referral->reward?->referrer?->amount); // '500.00' } return response()->noContent(); });
Keep the click ID
// bootstrap/app.php ->withMiddleware(function (Middleware $middleware) { $middleware->web(append: ['clikgate']); }) // a controller: save it with your own record Application::create(['reference' => 'APP-55231', 'click_id' => $request->clikgateClickId()]);
- The middleware keeps a
?cgid=…in the first-party_cg_cgidcookie, which the web script also reads. - The provider excludes that cookie from
EncryptCookies, so the web script can read it. $request->clikgateInstallation()reads the app'sClikgate-Installationheader (foridentifyUser): anInstallation(->appId,->installationId) ornullwhen it is missing or invalid. Pass it toidentifyUserasinstallationas it is. It works with or without the middleware.
Keep the click ID longer (Safari)
Safari, and every browser on iPhone, keeps a click ID saved by a script for up to 7 days (sometimes less). When your server saves it, it lasts as long as you choose, up to the browser's limit.
- Persist it from the query: the
clikgatemiddleware above does it on every page of thewebgroup, with the_cg_kept=smarker (goals then reportkept_by: server_cookie). - The
/cg/keeproute, for pages Laravel doesn't render (a static or cached landing page): register it, and adddata-server-endpoint="/cg/keep"to the web script.
// routes/web.php Route::clikgateKeep('/cg/keep');
<script src="https://sdk.clikgate.com/v1/static/clikgate.js" data-web-key="cgw_test_…" data-server-endpoint="/cg/keep" async></script>
- Same server only. The route must be served by the same host as the website (same scheme, host and port), because the cookie is first-party.
- CSRF: the macro removes Laravel's CSRF middleware (
ValidateCsrfToken) from this one route, because the web script has no CSRF token. The route checks the origin itself (Sec-Fetch-Site: same-origin, else anOriginequal to the host), accepts only a JSON body of at most 1 KB with the same valid click ID inclick_idandpage_click_id, and changes nothing but these two cookies. Every answer is empty withCache-Control: no-store, private; it never redirects and never echoes or logs what it receives. - Settings:
cookie.days(1 to 400, default 30) andcookie.domaininconfig/clikgate.php.Secureis always on unlesscookie.keep_secureis false. The cookie name comes fromclick_id_param(elsecgid), never from the request. - The cookie is readable by the page on purpose (not
HttpOnly, and excluded fromEncryptCookies): the web script needs to read it. It only holds the click ID. - Visitor context for goals:
Clikgate::clickIds()->context($request)returnsclickId,keptBy,browserEngineandplatform, worked out in the SDK from the cookie and theUser-Agent(the User-Agent itself is never sent):Clikgate::goal('account_opened', ['reference' => $application->reference, ...Clikgate::clickIds()->context($request)]). Allowed in private mode. - Hashed email and phone for ad networks: when the business has turned on matching by hashed email or phone for a destination, add
\Clikgate\HashForAds::hash($email, $phone)to a goal's options (hashedEmail,hashedPhoneE164,hashedPhoneDigits; see theclikgate/clikgate-phpREADME). In private mode, hash on your own server: Clikgate never hashes for you there.
Identify your users
Full guide: https://clikgate.com/docs/identify-users. Path A (default): set CLIKGATE_IDENTITY_SECRET (Developers › SDKs › your app › Set up identity › Identity secret) on the server only, and add one field to your sign-in and "current user" responses; the app passes it to the mobile SDK's identifyUser(). For several apps, CLIKGATE_IDENTITY_SECRETS is a JSON object of app IDs to secrets.
return response()->json(['user' => $user, 'clikgateIdentityToken' => Clikgate::createIdentityToken((string) $user->id)]); Clikgate::createIdentityToken((string) $user->id, ['appId' => 'app_…']); // several apps
Path B: the installation header, no secret or token. The mobile SDK gives your app a Clikgate-Installation header (<app_id>:<installation_id>, not a secret), which the app sends to your server with its sign-in request and signed-in requests. After your own sign-in check succeeds, and at every signed-in app open, pass it to Clikgate::identifyUser() as installation with your signed-in user's ID. Your server never needs to know which Clikgate app ID belongs to which platform. Clikgate accepts installations active in the last 7 days.
- The customer ID always comes from your own authenticated user. The header only names the app installation. Call
Clikgate::identifyUser()only after your sign-in check succeeds, and never read the customer ID from the request. - A missing or invalid header is ignored (
null, never an error or a log line): skip the call. Parsing is strict:app_…, one colon, a lowercase UUID, at most 128 characters, trimmed. appIdis optional. With only an installation ID, Clikgate finds the app. If the same installation ID is active in several of your apps (iOS apps sharing a Keychain access group can share one), the API answers409 installation_in_several_apps, aConflictExceptionwith paramapp_id: sendappIdtoo.
// After your own sign-in check (Auth::attempt), with the signed-in user's ID if (Auth::attempt($credentials) && ($installation = $request->clikgateInstallation()) !== null) { Clikgate::identifyUser(['installation' => $installation, 'customerId' => (string) Auth::id()]); }
Customers from before Clikgate
Tell Clikgate who was already your customer before you added it, so they are never counted as a referral or a new customer. Send the account's creation date with the identity token (version 2) or from your server, and import the rest of your existing customers once. Use your own customer IDs, never emails or phone numbers: Clikgate stores a keyed fingerprint of each imported ID, not the ID itself. Not available in private mode. Guide: https://clikgate.com/docs/identify-users.
Clikgate::createIdentityToken((string) $user->id, ['customerSince' => $user->created_at]); // version 2 Clikgate::knownCustomers()->import([['customerId' => 'u_10482', 'customerSince' => '2024-03-02']]);
Queued sending (recommended)
Set CLIKGATE_QUEUE=redis (any queue connection) and, optionally, CLIKGATE_QUEUE_NAME.
Clikgate::goal()then dispatches aClikgate\Laravel\Jobs\SendGoaljob, and the queue retries it on network errors, timeouts and HTTP 429, 500, 502, 503 and 504.- Each send uses a random
Idempotency-Key(reused across the HTTP retries inside one attempt), and the API ignores a second event with the same goal and reference, so a queue retry never counts twice. - Without a queue,
goal()usesCLIKGATE_SEND_MODE:sync(the default),after_responseorbackground.
Everything else
Clikgate::payments()->fromPaystack($verifyResponse)(andfromFlutterwave,fromMonnify,fromStripe,confirm([...])): confirm a payment right after your own verification with the gateway, never with data from the browser or the app (see the PHP SDK's Payments section).Clikgate::goal('order_paid', ['reference' => 'T123456', 'provider' => Provider::Paystack])reports a payment on a Payment goal; results carrystatus(GoalStatus:counted,waiting,received,refused). See the PHP SDK's Payment goals section.Clikgate::goals()->send(…),Clikgate::links(),Clikgate::clickIds()andClikgate::api(). Link methods return typed models ($link->shortUrl) that keep array access ($link['short_url']).Clikgate::referrals()->getOrCreateReferrer('rpg_01J…', ['customerId' => $customerId, 'code' => 'ADA2024'])creates the user's referrer with your own code instead of a generated one (2.1.1 or newer; 3-32 letters, digits,-or_, stored exactly as you send it and unique in your organisation ignoring case; errors:ConflictExceptioncode_taken(409),InvalidRequestExceptioninvalid_codeorreserved_link_ending(422)). It applies only when the referrer is created: later calls for the same user return the same referrer and code.externalCodekeeps a code from an older referral system working alongside it.Clikgate::referrals(),Clikgate::privacy(),Clikgate::people(),Clikgate::installs()andClikgate::codes(): typed resources (see the PHP SDK's "Referrals, privacy, people, installs and codes" section).Clikgate::verifyWebhook($request->getContent(), $request->header('Clikgate-Signature'), $secret)returns aClikgate\Model\WebhookEvent:asReferral(),asReferrer(),asGoalEvent(),asInstall(),asPayment(),asConversion(),asDeviceChange(); compare$event->typewith theEventTypestring constants;$event['type']keeps working.app(\Clikgate\Clikgate::class)gives the client itself.
See clikgate/clikgate-php. The full example is in examples/routes/web.php.
Licence: MIT. Security: report vulnerabilities to support@clikgate.com; see the trust centre.