Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
[Skip CI] Update Events & Webhooks docs
Damian Legawiecfaa0d34aa383
diff --git a/docs/developer/customization/event-subscribers.mdx b/docs/developer/core-concepts/events.mdxsimilarity index 66%rename from docs/developer/customization/event-subscribers.mdxrename to docs/developer/core-concepts/events.mdxindex 72df3b8d48..8de3755608 100644--- a/docs/developer/customization/event-subscribers.mdx+++ b/docs/developer/core-concepts/events.mdx@@ -1,8 +1,12 @@----title: Event Subscribers-description: Learn how to listen and react to events in Spree using the subscriber pattern.+title: Events+description: Learn how Spree's event system works and how to subscribe to events.---+<Warning>+ Events are part of the upcoming Spree 5.3 release slated for January 2026.+</Warning>+## OverviewSpree includes a powerful event system that allows you to react to various actions happening in your store. When something happens (an order is completed, a product is created, etc.), Spree publishes an event that your code can subscribe to and handle.@@ -17,7 +21,7 @@ This pattern enables loose coupling between components and makes it easy to:## How Events Work-Spree's event system is built on top of `ActiveSupport::Notifications` but provides a cleaner, more Rails-like API through:+Spree's event system is built on top of [`ActiveSupport::Notifications`](https://api.rubyonrails.org/classes/ActiveSupport/Notifications.html) but provides a cleaner, more Rails-like API through:1. **`Spree::Events`** - The main module for publishing and subscribing to events2. **`Spree::Subscriber`** - Base class for creating event subscribers@@ -116,9 +120,15 @@ When your subscriber receives an event, you get a `Spree::Event` object with:def handle(event)event.id # => "550e8400-e29b-41d4-a716-446655440000" (UUID)event.name # => "order.complete"+ event.store_id # => 1 (ID of the store where the event originated)event.payload # => { "id" => 1, "number" => "R123456", ... }- event.metadata # => { "spree_version" => "5.1.0", "store_id" => "1" }+ event.metadata # => { "spree_version" => "5.1.0" }event.created_at # => Time when event was published++ # Helper methods+ event.store # => Spree::Store instance (lazy loaded)+ event.resource_type # => "order" (extracted from name)+ event.action # => "complete" (extracted from name)end```@@ -194,13 +204,6 @@ Models with lifecycle events enabled include: `Order`, `Payment`, `Price`, `Ship| `price.updated` | Price was updated || `price.deleted` | Price was deleted |-### Stock Events--| Event | Description |-|-------|-------------|-| `product.out_of_stock` | Product has no stock left for any variant |-| `product.back_in_stock` | Product was out of stock and now has stock again |-### Customer Events| Event | Description |@@ -223,6 +226,8 @@ Models with lifecycle events enabled include: `Order`, `Payment`, `Price`, `Ship|-------|-------------|| `product.activate` | Product status changed to active || `product.archive` | Product status changed to archived |+| `product.out_of_stock` | Product has no stock left for any variant |+| `product.back_in_stock` | Product was out of stock and now has stock again |## Publishing Custom Events@@ -248,11 +253,182 @@ Use `Spree::Events.publish` directly:```rubySpree::Events.publish('inventory.low_stock',- { variant_id: variant.id, quantity: variant.total_on_hand },- { model_class: 'Spree::Variant', model_id: variant.id }+ { variant_id: variant.id, quantity: variant.total_on_hand })```+## Event Serializers++Event payloads are generated by dedicated serializer classes. Each model that publishes events needs a corresponding serializer in the `Spree::Events` namespace.++### How Serializers Work++When a model publishes an event, Spree looks for a serializer class matching the model name:++- `Spree::Order` → `Spree::Events::OrderSerializer`+- `Spree::Product` → `Spree::Events::ProductSerializer`+- `Spree::Payment` → `Spree::Events::PaymentSerializer`++The serializer converts the model into a hash that becomes the event payload. This ensures consistent, controlled data in your events rather than exposing all model attributes.++### Built-in Serializers++Spree includes serializers for all core models in [`app/serializers/spree/events/`](https://github.com/spree/spree/tree/main/core/app/serializers/spree/events):++| Serializer | Model |+|------------|-------|+| [`OrderSerializer`](https://github.com/spree/spree/blob/main/core/app/serializers/spree/events/order_serializer.rb) | Orders with totals, states, timestamps |+| [`ProductSerializer`](https://github.com/spree/spree/blob/main/core/app/serializers/spree/events/product_serializer.rb) | Products with pricing and status |+| [`PaymentSerializer`](https://github.com/spree/spree/blob/main/core/app/serializers/spree/events/payment_serializer.rb) | Payments with amounts and states |+| [`ShipmentSerializer`](https://github.com/spree/spree/blob/main/core/app/serializers/spree/events/shipment_serializer.rb) | Shipments with tracking info |+| [`LineItemSerializer`](https://github.com/spree/spree/blob/main/core/app/serializers/spree/events/line_item_serializer.rb) | Line items with quantity and pricing |+| [`VariantSerializer`](https://github.com/spree/spree/blob/main/core/app/serializers/spree/events/variant_serializer.rb) | Variants with SKU and pricing |+| ... | [And many more](https://github.com/spree/spree/tree/main/core/app/serializers/spree/events) |++### Creating a Custom Serializer++For custom models or to add attributes to existing events, create a serializer:++```ruby app/serializers/spree/events/order_serializer.rb+module Spree+ module Events+ class OrderSerializer < BaseSerializer+ protected++ def attributes+ {+ id: resource.id,+ number: resource.number,+ state: resource.state.to_s,+ total: money(resource.total),+ currency: resource.currency,+ email: resource.email,+ completed_at: timestamp(resource.completed_at),+ created_at: timestamp(resource.created_at),+ updated_at: timestamp(resource.updated_at)+ }+ end+ end+ end+end+```++### BaseSerializer Helpers++The `Spree::Events::BaseSerializer` provides helpful methods:++```ruby+class MySerializer < Spree::Events::BaseSerializer+ protected++ def attributes+ {+ id: resource.id, # Access the model via `resource`+ amount: money(resource.total), # Converts to decimal+ shipped_at: timestamp(resource.shipped_at), # ISO8601 format+ name: attribute(:name) # Safe attribute access (nil if missing)+ }+ end+end+```++| Method | Description |+|--------|-------------|+| `resource` | The model instance being serialized |+| `context` | Hash with event context (event_name, triggered_at) |+| `money(amount)` | Converts money to decimal value |+| `timestamp(time)` | Formats time as ISO8601 string |+| `attribute(name)` | Safely gets attribute (returns nil if missing) |++### Overriding Built-in Serializers++To customize the payload for existing events, create your own serializer that overrides Spree's:++```ruby app/serializers/spree/events/order_serializer.rb+module Spree+ module Events+ class OrderSerializer < BaseSerializer+ protected++ def attributes+ {+ # Include standard attributes+ id: resource.id,+ number: resource.number,+ state: resource.state.to_s,+ total: money(resource.total),++ # Add custom attributes+ custom_field: resource.custom_field,+ loyalty_points: calculate_loyalty_points,++ # Include related data+ line_item_count: resource.line_items.count,+ shipping_method: resource.shipments.first&.shipping_method&.name+ }+ end++ private++ def calculate_loyalty_points+ (resource.total.to_f * 10).to_i+ end+ end+ end+end+```++<Warning>+When overriding serializers, make sure to include all attributes that webhooks and subscribers depend on. Removing attributes may break integrations.+</Warning>++### Serializers for Custom Models++If you add a custom model that publishes events, you must create a serializer:++```ruby app/models/my_app/subscription.rb+module MyApp+ class Subscription < Spree.base_class+ publishes_lifecycle_events++ def renew!+ update!(renewed_at: Time.current)+ publish_event('subscription.renewed')+ end+ end+end+```++```ruby app/serializers/spree/events/subscription_serializer.rb+module Spree+ module Events+ class SubscriptionSerializer < BaseSerializer+ protected++ def attributes+ {+ id: resource.id,+ plan_name: resource.plan_name,+ status: resource.status,+ user_id: resource.user_id,+ renewed_at: timestamp(resource.renewed_at),+ expires_at: timestamp(resource.expires_at),+ created_at: timestamp(resource.created_at)+ }+ end+ end+ end+end+```++If you try to publish an event without a serializer, Spree raises a helpful error:++```+Spree::Publishable::MissingSerializerError:+ Missing event serializer for MyApp::Subscription.+ Please create Spree::Events::SubscriptionSerializer that inherits from Spree::Events::BaseSerializer.+```+## Registering SubscribersSubscribers in `app/subscribers/` are automatically registered during Rails initialization.@@ -340,8 +516,7 @@ Use the `emit_webhook_event` matcher (if available) or stub the events:it 'publishes order.complete event' doexpect(Spree::Events).to receive(:publish).with('order.complete',- hash_including('id' => order.id),- hash_including(model_class: 'Spree::Order')+ hash_including('id' => order.id))order.complete!@@ -413,7 +588,7 @@ end## Custom Event Adapters-Spree's event system uses an adapter pattern, making it possible to swap the underlying event infrastructure. By default, Spree uses `ActiveSupport::Notifications`, but you can create custom adapters for other backends like Kafka, RabbitMQ, or Redis Pub/Sub.+Spree's event system uses an adapter pattern, making it possible to swap the underlying event infrastructure. By default, Spree uses [`ActiveSupport::Notifications`](https://api.rubyonrails.org/classes/ActiveSupport/Notifications.html), but you can create custom adapters for other backends like Kafka, RabbitMQ, or Redis Pub/Sub.### Configuring a Custom Adapter@@ -493,5 +668,3 @@ See `Spree::Events::Adapters::ActiveSupportNotifications` for a complete referen## Related Documentation- [Webhooks](/developer/core-concepts/webhooks) - HTTP callbacks for external integrations-- [Dependencies](/developer/customization/dependencies) - Customizing Spree services-- [Decorators](/developer/customization/decorators) - Extending Spree classesdiff --git a/docs/developer/core-concepts/webhooks.mdx b/docs/developer/core-concepts/webhooks.mdxnew file mode 100644index 0000000000..133105f460--- /dev/null+++ b/docs/developer/core-concepts/webhooks.mdx@@ -0,0 +1,362 @@+---+title: Webhooks+description: Send real-time HTTP notifications to external services when events occur in your store.+---++<Warning>+ Webhooks are part of the upcoming Spree 5.3 release slated for January 2026.+</Warning>++## Overview++Webhooks allow your Spree store to send real-time HTTP POST notifications to external services when events occur. When an order is completed, a product is updated, or inventory changes, Spree can automatically notify your CRM, fulfillment service, analytics platform, or any other system.++Webhooks are built on top of Spree's [event system](/developer/core-concepts/events), providing:++- **Multi-store support** - Each store has its own webhook endpoints+- **Event filtering** - Subscribe to specific events or patterns with wildcards+- **Secure delivery** - HMAC-SHA256 signatures for payload verification+- **Automatic retries** - Failed deliveries retry with exponential backoff+- **Full audit trail** - Track every delivery attempt with response codes and timing++## How Webhooks Work++```+Event Published → WebhookEventSubscriber → Find Matching Endpoints → Queue Delivery Jobs → HTTP POST with Signature+```++1. An event is published (e.g., `order.completed`)+2. The `WebhookEventSubscriber` receives all events+3. It finds active webhook endpoints subscribed to that event+4. For each endpoint, it creates a `WebhookDelivery` record and queues a job+5. The job sends an HTTP POST request with the event payload and HMAC signature++## Creating Webhook Endpoints++### Via Admin Panel++Navigate to **Settings → Developers → Webhooks** in the admin panel to create and manage webhook endpoints.++### Via Code++```ruby+endpoint = Spree::WebhookEndpoint.create!(+ store: Spree::Store.default,+ url: 'https://example.com/webhooks/spree',+ subscriptions: ['order.*', 'product.created'],+ active: true+)++# The secret_key is auto-generated+endpoint.secret_key # => "a1b2c3d4e5f6..." (64-character hex string)+```++### Endpoint Attributes++| Attribute | Type | Description |+|-----------|------|-------------|+| `url` | String | The HTTPS endpoint URL to receive webhooks |+| `active` | Boolean | Enable/disable delivery to this endpoint |+| `subscriptions` | Array | Event patterns to subscribe to |+| `secret_key` | String | Auto-generated key for HMAC signature verification |+| `store_id` | Integer | The store this endpoint belongs to |++## Event Subscriptions++The `subscriptions` attribute controls which events trigger webhooks to this endpoint.++### Subscribe to Specific Events++```ruby+endpoint.subscriptions = ['order.completed', 'order.canceled']+```++### Subscribe to Event Patterns++Use wildcards to subscribe to multiple related events:++```ruby+# All order events+endpoint.subscriptions = ['order.*']++# All creation events+endpoint.subscriptions = ['*.created']++# Multiple patterns+endpoint.subscriptions = ['order.*', 'payment.*', 'shipment.shipped']+```++### Subscribe to All Events++Leave subscriptions empty or use `*` to receive all events:++```ruby+endpoint.subscriptions = [] # All events+endpoint.subscriptions = ['*'] # All events (explicit)+```++## Webhook Payload++Each webhook delivery sends a JSON payload with the following structure:++```json+{+ "id": "550e8400-e29b-41d4-a716-446655440000",+ "name": "order.completed",+ "created_at": "2024-01-15T10:30:00Z",+ "data": {+ "id": 123,+ "number": "R123456789",+ "state": "complete",+ "total": "99.99",+ "item_count": 3+ },+ "metadata": {+ "spree_version": "5.1.0"+ }+}+```++| Field | Description |+|-------|-------------|+| `id` | Unique UUID for this event |+| `name` | Event name (e.g., `order.completed`) |+| `created_at` | ISO8601 timestamp when event occurred |+| `data` | Serialized resource data |+| `metadata` | Additional context including Spree version |++## HTTP Request Details++### Headers++Each webhook request includes these headers:++| Header | Description |+|--------|-------------|+| `Content-Type` | `application/json` |+| `User-Agent` | `Spree-Webhooks/1.0` |+| `X-Spree-Webhook-Event` | Event name (e.g., `order.completed`) |+| `X-Spree-Webhook-Signature` | HMAC-SHA256 signature for verification |++### Verifying Webhook Signatures++To ensure webhooks are genuinely from your Spree store, verify the signature:++```ruby+# In your webhook receiver+def verify_webhook(request)+ payload = request.body.read+ signature = request.headers['X-Spree-Webhook-Signature']+ secret_key = ENV['SPREE_WEBHOOK_SECRET'] # Your endpoint's secret_key++ expected = OpenSSL::HMAC.hexdigest('SHA256', secret_key, payload)++ ActiveSupport::SecurityUtils.secure_compare(signature, expected)+end+```++Example in a Rails controller:++```ruby+class WebhooksController < ApplicationController+ skip_before_action :verify_authenticity_token++ def receive+ unless verify_signature+ head :unauthorized+ return+ end++ event = JSON.parse(request.body.read)++ case event['name']+ when 'order.completed'+ handle_order_completed(event['data'])+ when 'product.updated'+ handle_product_updated(event['data'])+ end++ head :ok+ end++ private++ def verify_signature+ payload = request.body.read+ request.body.rewind++ signature = request.headers['X-Spree-Webhook-Signature']+ expected = OpenSSL::HMAC.hexdigest('SHA256', ENV['SPREE_WEBHOOK_SECRET'], payload)++ ActiveSupport::SecurityUtils.secure_compare(signature.to_s, expected)+ end+end+```++## Delivery Status & Retries++### Automatic Retries++Failed webhook deliveries automatically retry up to 5 times with exponential backoff. This handles temporary network issues and endpoint downtime.++### Checking Delivery Status++```ruby+endpoint = Spree::WebhookEndpoint.find(id)++# Recent deliveries+endpoint.webhook_deliveries.recent++# Filter by status+endpoint.webhook_deliveries.successful+endpoint.webhook_deliveries.failed+endpoint.webhook_deliveries.pending++# Filter by event+endpoint.webhook_deliveries.for_event('order.completed')+```++### Delivery Attributes++| Attribute | Description |+|-----------|-------------|+| `event_name` | Name of the event delivered |+| `payload` | Complete webhook payload sent |+| `response_code` | HTTP status code (nil if pending) |+| `success` | Boolean indicating 2xx response |+| `execution_time` | Delivery time in milliseconds |+| `error_type` | `'timeout'`, `'connection_error'`, or nil |+| `request_errors` | Error message details |+| `response_body` | Response from endpoint (truncated) |+| `delivered_at` | Timestamp of delivery attempt |++## Configuration++### Enabling/Disabling Webhooks++Webhooks are enabled by default. To disable globally:++```ruby+# config/initializers/spree.rb+Spree::Api::Config.webhooks_enabled = false+```++### SSL Verification++SSL verification is enabled by default in production. In development, it's disabled to allow testing with self-signed certificates:++```ruby+# config/initializers/spree.rb+Spree::Api::Config.webhooks_verify_ssl = true # Force SSL verification+Spree::Api::Config.webhooks_verify_ssl = false # Disable (not recommended for production)+```++## Available Events++Webhooks can subscribe to any event in Spree's event system. See [Events](/developer/core-concepts/events#available-events) for a complete list.++Common webhook events include:++| Event | Description |+|-------|-------------|+| `order.completed` | Order checkout finished |+| `order.canceled` | Order was canceled |+| `order.paid` | Order is fully paid |+| `shipment.shipped` | Shipment was shipped |+| `payment.paid` | Payment was completed |+| `product.created` | New product created |+| `product.updated` | Product was modified |+| `customer.created` | New customer registered |++## Testing Webhooks++### In Development++Use tools like [ngrok](https://ngrok.com) or [webhook.site](https://webhook.site) to test webhooks locally:++```ruby+# Create a test endpoint+endpoint = Spree::WebhookEndpoint.create!(+ store: Spree::Store.default,+ url: 'https://your-ngrok-url.ngrok.io/webhooks',+ subscriptions: ['order.*'],+ active: true+)++# Trigger an event+order = Spree::Order.complete.last+order.publish_event('order.completed')++# Check delivery+endpoint.webhook_deliveries.last.success?+```++### In Tests++```ruby+RSpec.describe 'Webhook delivery' do+ let(:store) { create(:store) }+ let(:endpoint) { create(:webhook_endpoint, store: store, subscriptions: ['order.completed']) }+ let(:order) { create(:completed_order_with_totals, store: store) }++ it 'delivers webhook when order completes' do+ stub_request(:post, endpoint.url).to_return(status: 200)++ expect {+ order.publish_event('order.completed')+ }.to have_enqueued_job(Spree::WebhookDeliveryJob)+ end+end+```++## Best Practices++<CardGroup cols={2}>+ <Card title="Respond quickly" icon="bolt">+ Return a 2xx response as fast as possible. Process webhook data asynchronously in a background job.+ </Card>++ <Card title="Verify signatures" icon="shield">+ Always verify the `X-Spree-Webhook-Signature` header to ensure the webhook is authentic.+ </Card>++ <Card title="Handle duplicates" icon="copy">+ Use the event `id` to detect and handle duplicate deliveries. Webhooks may be retried.+ </Card>++ <Card title="Subscribe selectively" icon="filter">+ Only subscribe to events you need. Use specific patterns rather than `*` when possible.+ </Card>+</CardGroup>++## Troubleshooting++### Webhooks Not Delivering++1. Check that webhooks are enabled: `Spree::Api::Config.webhooks_enabled`+2. Verify the endpoint is active: `endpoint.active?`+3. Confirm the endpoint subscribes to the event: `endpoint.subscribed_to?('order.completed')`+4. Check the event has a `store_id` matching the endpoint's store++### Signature Verification Failing++1. Ensure you're using the raw request body (not parsed JSON)+2. Verify you're using the correct `secret_key` for this endpoint+3. Check that no middleware is modifying the request body++### Deliveries Failing++Check the delivery record for details:++```ruby+delivery = endpoint.webhook_deliveries.failed.last+delivery.error_type # => 'timeout' or 'connection_error'+delivery.request_errors # => Error message+delivery.response_code # => HTTP status code+delivery.response_body # => Response from your endpoint+```++## Related Documentation++- [Events](/developer/core-concepts/events) - Understanding Spree's event system+- [Dependencies](/developer/customization/dependencies) - Customizing Spree servicesdiff --git a/docs/docs.json b/docs/docs.jsonindex 44e0fada70..618ae00ee8 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -35,6 +35,14 @@{"source": "/developer/admin/permissions","destination": "/developer/customization/permissions"+ },+ {+ "source": "/developer/customization/event-subscribers",+ "destination": "/developer/core-concepts/events"+ },+ {+ "source": "/developer/customization/webhooks",+ "destination": "/developer/core-concepts/webhooks"}],"contextual": {@@ -99,6 +107,8 @@"developer/core-concepts/adjustments","developer/core-concepts/addresses","developer/core-concepts/metafields",+ "developer/core-concepts/events",+ "developer/core-concepts/webhooks","developer/core-concepts/i18n","developer/core-concepts/search-filtering","developer/core-concepts/slugs",@@ -144,7 +154,6 @@"developer/customization/authentication","developer/customization/checkout","developer/customization/permissions",- "developer/customization/event-subscribers","developer/customization/dependencies","developer/customization/decorators","developer/customization/model-preferences",