diff --git a/docs/developers/sockets.md b/docs/developers/sockets.md index 229cb12..fe931f1 100644 --- a/docs/developers/sockets.md +++ b/docs/developers/sockets.md @@ -2,6 +2,130 @@ title: Develop with Sockets sidebar_position: 3 slug: /developers/sockets +toc_min_heading_level: 2 +toc_max_heading_level: 5 --- -# Using Fleetbase Sockets +# Developing with Fleetbase Sockets + +Real-time functionality is critical for modern logistics operations. Fleetbase utilizes SocketCluster, an efficient WebSocket-based pub/sub messaging system, to enable real-time features like location tracking and status updates. This guide will help you understand how to connect to and use Fleetbase's WebSocket channels effectively. + +## Setting Up SocketCluster Client + +Before you can subscribe to any channel, you need to set up your SocketCluster client. Here’s how you can do it: + +### 1. Installation + +First, install the SocketCluster client if it's not already included in your project: + +```bash +npm install socketcluster-client +``` + +### 2. Connecting to the Server + +Use the following JavaScript code to connect to the SocketCluster server: + +```javascript +import socketClusterClient from 'socketcluster-client'; + +// Setup to connect to the Fleetbase Socket (socket.fleetbase.io) on port 8000 +const socketConfig = { + hostname: 'socket.fleetbase.io', + secure: true, + port: 8000, + path: '/socketcluster/', + connectTimeout: 10000, + disconnectOnUnload: true, +}; + +const socketClusterClient = socketClusterClient.create(socketConfig); + +// Listen for successful connection +(async () => { + for await (let event of socketClusterClient.listener('connect')) { + console.log('Connected to the server!'); + } +})(); + +// Listen for connection error +(async () => { + for await (let event of socketClusterClient.listener('error')) { + console.error('Connection Error:', event); + } +})(); +``` + +### 3. Subscribing to Channels + +Once your client is set up and connected, you can subscribe to specific resource channels based on the `{type}.{id}` format. Each resource, like a driver, has its own channel. + +#### Example: Subscribing to a Driver's Channel + +Here's how to subscribe to a driver’s channel for real-time updates: + +```javascript +// Replace 'driver_iox3ekU' with the actual driver ID +const channelName = 'driver.driver_iox3ekU'; +const channel = socket.subscribe(channelName); + +// Listen to channel for events +await channel.listener('subscribe').once(); + +// Listen for channel subscription +(async () => { + for await (let output of channel) { + const { event, data } = output; + + // Handle the location change of driver + if (event === 'driver.location_changed') { + showDriverOnMap(data.location); + } + } +})(); +``` + +## Handling Data + +Data received through channels can include a variety of information depending on the resource type. For drivers, it might include location coordinates, status updates, and other telemetry data. + +### Processing Incoming Data + +```javascript +(async () => { + for await (let output of channel) { + const { event, data } = output; + if (event === 'driver.location_changed') { + console.log(`${event} - Driver location: Latitude ${data.location.coordinates[0]}, Longitude ${data.location.coordinates[1]}`); + } + } +})(); +``` + +The incoming socket data will be structured like so: + +```json +{ + "id": "", + "api_version": "", + "event": "", + "created_at": "", + "data": { + "id": "", + ...other attributes + "additionalData": {} + } +} +``` + +The data will typically be the updated properties of the resource subscribed to, the `event` will name the type of event. For example it could be `driver.location_changed` or `driver.updated`. + +## Best Practices + +- **Error Handling:** Implement robust error handling, especially for connection issues and failed subscriptions. +- **Security:** Ensure that all communications are secured using HTTPS and WSS, and that authentication tokens are managed securely. +- **Resource Management:** Unsubscribe from channels when no longer needed to prevent memory leaks and unnecessary data traffic. + +## Conclusion + +By integrating Fleetbase's real-time capabilities using SocketCluster, you can significantly enhance the responsiveness and efficiency of your logistics operations. This guide provides the foundational knowledge needed to start developing with Fleetbase sockets, enabling dynamic, real-time interactions across your logistics platforms. diff --git a/docs/developers/webhooks.md b/docs/developers/webhooks.md index 62a7001..459fb3a 100644 --- a/docs/developers/webhooks.md +++ b/docs/developers/webhooks.md @@ -2,6 +2,137 @@ title: Develop with Webhooks sidebar_position: 3 slug: /developers/webhooks +toc_min_heading_level: 2 +toc_max_heading_level: 5 --- -# Using Fleetbase Webhooks +# Developing with Fleetbase Webhooks + +Webhooks in Fleetbase provide a powerful way to integrate real-time event-driven functionalities into your external applications or services. By setting up webhooks, your system can instantly react to various events occurring within the Fleetbase platform. + +## Setting Up Webhooks + +Fleetbase provides an easy to use interface for creating and monitoring webhook events. + +### Creating a Webhook + +1. **Navigate to the Developers Section:** +Access the Fleetbase console and go to the Developers section, then select the Webhooks option. + +2. **Specify the Receiving Endpoint:** +Enter the URL of the endpoint where you want Fleetbase to send webhook events. This endpoint should be a server you control which is capable of receiving HTTPS POST requests. + +3. **Select Events:** +Choose the specific events you wish to receive notifications for. You can subscribe to individual events related to resources like orders, drivers, or vehicles, or opt to receive all available events. + +
+ +
+ + +### Configuring Your Endpoint + +Ensure that your endpoint is set up to: + +- Accept HTTPS POST requests. +- Validate incoming requests to ensure they are coming from Fleetbase. +- Respond correctly to HTTP challenges (if applicable) to verify ownership of the endpoint. + +### Practical Uses of Webhooks + +Webhooks can be utilized in various scenarios such as: + +- **Order Updates**: Receive real-time notifications when orders are created, updated, or status changes. +- **Driver Monitoring**: Get alerts when a driver starts a route, completes a delivery, or updates their status. +- **Inventory Management**: Automatically update inventory levels in your ERP or inventory management system when sales or returns occur. + +### Testing Your Webhooks + +#### Manual Testing + +1. **Send Test Event:** +From the webhook configuration page in the Fleetbase console, use the functionality to send a test event to your endpoint. + +2. **Check Your Endpoint:** +Ensure that your server logs the incoming requests. Verify that the payload and headers are received as expected. + +#### Automated Testing + +Set up automated tests that simulate webhook calls using tools like Postman or curl. For example: + +```bash +curl -X POST https://your-endpoint.com/webhook -H 'Content-Type: application/json' -d '{"event":"order.updated","data":{"id":"order_xxxabc","status":"dispatched"}}' +``` + +## Processing Incoming Data + +An example of receiving a Fleetbase in a Laravel application. + +```php +input('event'); + $data = $request->input('data'); + + if ($event === 'driver.location_changed') { + $location = $data['location']; + try { + DriverManagement::updateLocation($data['id'], $location); + } catch (\Throwable $e) { + return response()->json(['error' => $e->getMessage()], 400); + } + } + } +} +``` + +The incoming webhook data will be structured like so: + +```json +{ + "id": "", + "api_version": "", + "event": "", + "created_at": "", + "data": { + "id": "", + ...other attributes + "additionalData": {} + } +} +``` + +The data will typically be the updated properties of the resource subscribed to, the `event` will name the type of event. For example it could be `driver.location_changed` or `driver.updated`. + +## Common Webhook Development Practices + +#### Security Practices + +- **Validate Payloads**: Always verify that the incoming data is from Fleetbase using signatures or comparing the IP address against known Fleetbase IPs. +- **Use HTTPS**: Ensure that your endpoint is secured with HTTPS to protect the data transmitted between Fleetbase and your server. + +#### Error Handling + +- **Responding to Failures**: Make sure to handle failures gracefully. If your endpoint encounters an error, it should log this error and respond with appropriate HTTP status codes. +- **Retries**: Understand Fleetbase's retry mechanism. Ensure your system can handle or ignore duplicate events in case of delivery retries. + +#### Scalability + +- **Asynchronous Processing**: Consider processing the webhook payloads asynchronously if the processing is resource-intensive, to quickly respond to incoming webhook calls. + +## Viewing Webhook Logs + +Fleetbase provides logging for each webhook event sent. You can view these logs in the console under the Webhooks section. This is useful for: + +- **Debugging**: Quickly identifying and resolving issues related to event handling. +- **Audit Trails**: Keeping track of what events were sent and when, including the payload and the response received by Fleetbase. + +## Conclusion + +Webhooks are a crucial feature for developing responsive and integrated logistic systems with Fleetbase. By following this guide, you can set up, test, and effectively use webhooks to enhance the capabilities of your applications, ensuring they remain synced with real-time data and events from Fleetbase. diff --git a/static/img/create-webhook.png b/static/img/create-webhook.png new file mode 100644 index 0000000..dbe12eb Binary files /dev/null and b/static/img/create-webhook.png differ