DEV Community

Cover image for Geofencing with Laravel
Walid LAGGOUNE
Walid LAGGOUNE

Posted on • Edited on

Geofencing with Laravel

Pulsetracker https://www.pulsestracker.com provides a powerful geofencing feature that allows you to monitor when devices enter or exit specific geographic areas. This guide will walk you through integrating Pulsetracker geofencing into your Laravel application, including creating geofences, handling webhooks, and verifying webhook signatures.

1. Setting Up Your Webhook Signature

To receive geofencing event notifications, you need to create a webhook signature in your Pulsetracker dashboard:

  1. Go to Dashboard > Tokens & Webhooks.

  2. Create a new webhook signature.

  3. Copy the generated signature for later use.

Without a valid webhook signature, Pulsetracker will not send webhook events.

2. Creating a Geofence

You can create a geofence using two methods:

Option 1: Using the Pulsetracker Dashboard

  1. Navigate to Dashboard > Geofencing.

  2. Click Add New Geofence.

  3. Set a name and draw the geofence polygon on the map.

  4. (Optional) Provide a webhook URL to receive entry/exit events.

  5. Assign the geofence to an app and save it.

Option 2: Using the HTTP API

To create a geofence programmatically, send a POST request to the Pulsetracker API.

Example: Creating a Geofence with Laravel HTTP Client

<?php
use Illuminate\Support\Facades\Http;

$response = Http::withToken('your_api_key')
    ->post('https://www.pulsestracker.com/api/geofences', [
        'name' => 'Warehouse Zone',
        'app_id' => 12345,
        'webhook_url' => 'https://yourdomain.com/webhook/geofence',
        'geometry' => json_encode([
            'geometry' => [
                'type' => 'Polygon',
                'coordinates' => [[[1,1], [1,2], [2,2], [2,1], [1,1]]]
            ]
        ]),
    ]);

if ($response->successful()) {
    echo "Geofence created: " . $response->json()['id'];
} else {
    echo "Error: " . $response->body();
}
Enter fullscreen mode Exit fullscreen mode

Handling Webhook Events

Pulsetracker sends a POST request to your webhook URL when a device enters or exits a geofence.

Webhook Payload Example

{
    "event": "inside",
    "point": {"type": "Point", "coordinates": [1.5, 1.5]},
    "device_id": 42,
    "geofence_id": 123,
    "location_received_at": 1700000000,
    "event_sent_at": 1700000005
}
Enter fullscreen mode Exit fullscreen mode

Webhook Headers

p-signature: {calculated_signature}
Enter fullscreen mode Exit fullscreen mode

Handling Webhooks in Laravel

Create a new middleware to verify webhook signatures:

<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class VerifyPulsetrackerSignature
{
    public function handle(Request $request, Closure $next)
    {
        $signature = $request->header('p-signature');
        $secret = config('pulsetracker.webhook_secret');

        if (!$this->verifySignature($request->all(), $secret, $signature)) {
            return response()->json(['error' => 'Invalid signature'], 403);
        }

        return $next($request);
    }

    private function verifySignature(array $payload, string $secret, string $signature): bool
    {
        $calculatedSignature = hash_hmac('sha256', json_encode($payload), $secret);
        return hash_equals($calculatedSignature, $signature);
    }
}
Enter fullscreen mode Exit fullscreen mode

Register the Middleware

In app/Http/Kernel.php, add the middleware:

protected $routeMiddleware = [
    'verify.pulsetracker' => \App\Http\Middleware\VerifyPulsetrackerSignature::class,
];
Enter fullscreen mode Exit fullscreen mode

Register the Webhook Route

Add the webhook route in routes/api.php:

use App\Http\Controllers\GeofenceWebhookController;

Route::post('/webhook/geofence', [GeofenceWebhookController::class, 'handle'])->middleware('verify.pulsetracker');
Enter fullscreen mode Exit fullscreen mode

Handling Webhook Events in Controller

Create a new controller to process geofencing events:

<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class GeofenceWebhookController extends Controller
{
    public function handle(Request $request)
    {
        // Process geofence event
        Log::info("Geofence event received", $request->all());

        return response()->json(['status' => 'success']);
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

With Pulsetracker’s (https://www.pulsestracker.com) geofencing API, you can easily monitor device movements and trigger actions when they enter or exit defined areas. Laravel’s robust HTTP client and event handling make it a great fit for integrating this feature seamlessly.

If you have any questions, check out the official Pulsetracker API documentation. 🚀

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools 🔁

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more