Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Verify carrier webhooks and unify them under one endpoint

Damian Legawiec4245264e3fe6
diff --git a/docs/v6/developer/how-to/custom-delivery-rate-provider.mdx b/docs/v6/developer/how-to/custom-delivery-rate-provider.mdx
index 4ba69abb40..d1d4f27c51 100644
--- a/docs/v6/developer/how-to/custom-delivery-rate-provider.mdx
+++ b/docs/v6/developer/how-to/custom-delivery-rate-provider.mdx
@@ -168,29 +168,55 @@ Once a parcel is moving, most carriers will tell you where it is. Spree keeps
that on a separate field from the fulfillment's own status, so a bounced parcel
never un-ships itself — see [Fulfillments](/v6/developer/core-concepts/fulfillments#statuses).
-Translate the carrier's vocabulary into Spree's in your gem, then hand it over:
+Spree owns the endpoint: every integration gets one at
+`POST /api/v3/webhooks/fulfillments/:integration_id` — the merchant pastes
+that URL into the carrier's webhook settings. Your job is one method on the
+integration:
```ruby
-Spree.fulfillment_update_tracking_workflow.call(
- fulfillment: fulfillment,
- tracking_status: 'out_for_delivery', # one of Spree::Fulfillment::TRACKING_STATUSES
- estimated_delivery_at: Time.parse(payload['eta']),
- details: payload.slice('status_detail', 'carrier')
-)
+class SpreeAcmeCarrier::Integration < Spree::Integration
+ preference :api_key, :password
+ preference :webhook_secret, :password
+
+ # Verify the signature against your secret, translate the payload, return
+ # UpdateTracking arguments plus the tracking code to match on — or nil for
+ # events you don't act on.
+ def parse_webhook_event(raw_post, headers)
+ raise Spree::Integration::WebhookSignatureError if preferred_webhook_secret.blank?
+
+ payload = AcmeCarrier.verify!(raw_post, headers, preferred_webhook_secret) # raises on a bad signature
+
+ return unless payload['type'] == 'shipment.status_changed'
+
+ {
+ tracking_code: payload['tracking_code'],
+ tracking_status: STATUS_MAP.fetch(payload['status'], 'unknown'), # Spree::Fulfillment::TRACKING_STATUSES
+ estimated_delivery_at: payload['eta'],
+ delivered_at: payload['delivered_scan_at'],
+ details: payload.slice('status_detail', 'carrier')
+ }
+ rescue AcmeCarrier::SignatureError => e
+ raise Spree::Integration::WebhookSignatureError, e.message
+ end
+end
```
-Two things it does for you: reporting `delivered` also confirms receipt on the
-fulfillment (setting `delivered_at`, which return windows count from), and an
-update that only carries a scan leaves an earlier estimate alone.
-
-Pass `delivered_at` from the carrier's delivering scan rather than letting it
-default to now — a webhook usually lands well after the parcel arrives, and the
-customer's return window starts at the doorstep.
-
-Do the translation in your gem, never in core: `unknown` keeps an unrecognised
-report visible instead of dropping it. A webhook endpoint should answer `200`
-even for parcels it does not recognise, or the carrier will retry a payload
-that can never succeed.
+The endpoint does the rest: signature failures answer `401` so a misconfigured
+sender notices, unmatched tracking codes and `nil` events are acknowledged with
+`200` so the carrier never retries a payload that cannot succeed, and matched
+events run through `Fulfillments::UpdateTracking` — reporting `delivered` also
+confirms receipt on the fulfillment, and an update carrying only a scan leaves
+an earlier estimate alone.
+
+Three rules worth keeping:
+
+- **Verify or refuse.** Raise `WebhookSignatureError` when no secret is
+ configured rather than accepting unsigned reports — a forged `delivered`
+ starts the customer's return window and, in the EU, the withdrawal clock.
+- **Pass `delivered_at` from the carrier's delivering scan**, not the webhook's
+ arrival time. The webhook usually lands well after the parcel does.
+- **Translate in your gem, never in core.** Map unrecognised carrier statuses
+ to `unknown` so the report stays visible instead of being dropped.
## Testing
diff --git a/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb b/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb
new file mode 100644
index 0000000000..f113cf1f02
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb
@@ -0,0 +1,73 @@
+module Spree
+ module Api
+ module V3
+ module Webhooks
+ # Carrier webhooks, addressed to the integration holding the carrier's
+ # credentials: POST /api/v3/webhooks/fulfillments/:integration_id.
+ #
+ # Mirrors the payments webhook endpoint: the integration verifies the
+ # signature synchronously (401 when it fails, so a misconfigured
+ # sender notices), translates the payload into core vocabulary, and
+ # anything unrecognised is acknowledged with 200 — carriers retry
+ # anything else, and there is nothing to retry for a parcel that is
+ # not ours. Unlike payments there is no job hand-off: recording a
+ # tracking update is a couple of database writes, well inside any
+ # sender's timeout.
+ class FulfillmentsController < ActionController::API
+ include ActionController::RateLimiting
+ include Spree::Core::ControllerHelpers::Store
+
+ RATE_LIMIT_RESPONSE = -> {
+ [429, { 'Content-Type' => 'application/json', 'Retry-After' => '60' },
+ [{ error: { code: 'rate_limit_exceeded', message: 'Too many requests' } }.to_json]]
+ }
+
+ rate_limit to: 120, within: 1.minute,
+ store: Rails.cache,
+ by: -> { request.remote_ip },
+ with: RATE_LIMIT_RESPONSE
+
+ def create
+ integration = current_store.integrations.active.find_by_prefix_id!(params[:integration_id])
+
+ event = integration.parse_webhook_event(request.raw_post, request.headers)
+ return head :ok if event.nil?
+
+ fulfillment = find_fulfillment(event[:tracking_code])
+ return head :ok if fulfillment.nil?
+
+ Spree.fulfillment_update_tracking_workflow.call(
+ fulfillment: fulfillment,
+ **event.except(:tracking_code)
+ )
+
+ head :ok
+ rescue Spree::Integration::WebhookSignatureError
+ head :unauthorized
+ rescue ActiveRecord::RecordNotFound
+ head :not_found
+ rescue StandardError => e
+ Rails.error.report(e, source: 'spree.webhooks.fulfillments')
+ head :ok
+ end
+
+ private
+
+ # Scoped to the store the verified integration belongs to — a
+ # tracking code can never address another tenant's parcel — and to
+ # parcels that shipped, so a recycled code cannot reopen an old one.
+ def find_fulfillment(tracking_code)
+ return if tracking_code.blank?
+
+ Spree::Fulfillment.
+ joins(:order).merge(current_store.orders).
+ where(tracking: tracking_code).
+ not_canceled.
+ reverse_chronological.
+ first
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index f0f9851432..a94024bc95 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -513,6 +513,7 @@ Spree::Core::Engine.add_routes do
# Webhooks (outside of store namespace — no API key authentication)
namespace :webhooks do
post 'payments/:payment_method_id', to: 'payments#create', as: :payment_webhook
+ post 'fulfillments/:integration_id', to: 'fulfillments#create', as: :fulfillment_webhook
end
end
end
diff --git a/spree/core/app/models/spree/integration.rb b/spree/core/app/models/spree/integration.rb
index 324a6beb91..6f2d19c07e 100644
--- a/spree/core/app/models/spree/integration.rb
+++ b/spree/core/app/models/spree/integration.rb
@@ -2,6 +2,12 @@ module Spree
class Integration < Spree.base_class
has_prefix_id :int
+ # Raised by {#parse_webhook_event} when a webhook's signature is missing
+ # or does not match this integration's secret. The webhook controller
+ # answers 401, so the sender knows its configuration is wrong rather than
+ # retrying forever.
+ WebhookSignatureError = Class.new(StandardError)
+
include Spree::SingleStoreResource
include Spree::PreferenceSchema
@@ -124,6 +130,25 @@ module Spree
self.class.integration_name
end
+ # Verifies and parses a provider webhook addressed to this integration.
+ #
+ # The base implementation accepts nothing: an integration that takes
+ # webhooks overrides this, verifies the signature against its own secret
+ # (raising {WebhookSignatureError} when it is missing or wrong), and
+ # returns the event translated into vocabulary core understands. Carrier
+ # integrations return {Spree::Fulfillments::UpdateTracking} keyword
+ # arguments plus +tracking_code+; +nil+ means "not an event we act on",
+ # which the endpoint acknowledges without doing anything.
+ #
+ # @param _raw_post [String] the request body exactly as received — HMAC
+ # signatures are computed over the raw bytes, so it must not be re-parsed
+ # or re-encoded before verification
+ # @param _headers [#[]] the request headers
+ # @return [Hash, nil]
+ def parse_webhook_event(_raw_post, _headers)
+ nil
+ end
+
# Checks if the integration can establish a connection.
# This is a base implementation that always returns true.
# Subclasses should override this method to implement their own connection validation logic.
diff --git a/spree/providers/easypost/app/controllers/spree_easypost/webhooks_controller.rb b/spree/providers/easypost/app/controllers/spree_easypost/webhooks_controller.rb
deleted file mode 100644
index 3704d61e0b..0000000000
--- a/spree/providers/easypost/app/controllers/spree_easypost/webhooks_controller.rb
+++ /dev/null
@@ -1,44 +0,0 @@
-module SpreeEasyPost
- # Receives EasyPost's `tracker.updated` webhooks and hands them to
- # {Spree::Fulfillments::UpdateTracking}.
- #
- # Always answers 200 once the payload has been read. A webhook endpoint that
- # returns an error gets retried, and there is nothing to retry for a tracker
- # we do not recognise — the parcel may belong to another system entirely.
- # Genuine failures are reported rather than escalated to the carrier.
- class WebhooksController < ActionController::Base
- protect_from_forgery with: :null_session
- skip_forgery_protection
-
- def create
- event = SpreeEasyPost::TrackerEvent.from_webhook(params)
- return head(:ok) if event.nil?
-
- fulfillment = find_fulfillment(event.tracking_code)
- return head(:ok) if fulfillment.nil?
-
- Spree.fulfillment_update_tracking_workflow.call(
- fulfillment: fulfillment,
- tracking_status: event.status,
- estimated_delivery_at: event.estimated_delivery_at,
- delivered_at: event.delivered_at,
- details: event.details
- )
-
- head :ok
- rescue StandardError => e
- Rails.error.report(e, handled: true, context: { tracking_code: params.dig(:result, :tracking_code) })
- head :ok
- end
-
- private
-
- # Matched on tracking code alone: EasyPost's webhook says nothing about
- # which store a parcel belongs to, and a tracking code is unique in
- # practice. Scoped to fulfillments that actually shipped so a recycled code
- # cannot reopen an old parcel's tracking.
- def find_fulfillment(tracking_code)
- Spree::Fulfillment.where(tracking: tracking_code).not_canceled.reverse_chronological.first
- end
- end
-end
diff --git a/spree/providers/easypost/app/models/spree_easypost/integration.rb b/spree/providers/easypost/app/models/spree_easypost/integration.rb
index 29db921633..a5c0f0efb0 100644
--- a/spree/providers/easypost/app/models/spree_easypost/integration.rb
+++ b/spree/providers/easypost/app/models/spree_easypost/integration.rb
@@ -3,6 +3,10 @@ module SpreeEasyPost
# issues separate test and production keys, so there is no mode toggle.
class Integration < Spree::Integration
preference :api_key, :password
+ # The shared secret configured on the EasyPost webhook; signs every
+ # delivery. Without it webhooks are refused — an unauthenticated report
+ # could otherwise mark parcels delivered, which starts return windows.
+ preference :webhook_secret, :password
# EasyPost's own documentation example address — used only to prove the
# key authenticates.
@@ -18,6 +22,19 @@ module SpreeEasyPost
'shipping'
end
+ # Verifies the EasyPost HMAC signature and translates `tracker.updated`
+ # payloads into UpdateTracking arguments. Non-tracker events (batches,
+ # refund confirmations) return nil and are acknowledged without action.
+ def parse_webhook_event(raw_post, headers)
+ raise Spree::Integration::WebhookSignatureError, 'webhook secret not configured' if preferred_webhook_secret.blank?
+
+ payload = EasyPost::Util.validate_webhook(raw_post, headers, preferred_webhook_secret)
+
+ SpreeEasyPost::TrackerEvent.from_webhook(payload)&.to_update_tracking_arguments
+ rescue EasyPost::Errors::SignatureVerificationError => e
+ raise Spree::Integration::WebhookSignatureError, e.message
+ end
+
def self.integration_name
SpreeEasyPost::PROVIDER_NAME
end
diff --git a/spree/providers/easypost/app/models/spree_easypost/tracker_event.rb b/spree/providers/easypost/app/models/spree_easypost/tracker_event.rb
index f1b64cbb9b..90ecb4b092 100644
--- a/spree/providers/easypost/app/models/spree_easypost/tracker_event.rb
+++ b/spree/providers/easypost/app/models/spree_easypost/tracker_event.rb
@@ -36,15 +36,12 @@ module SpreeEasyPost
# @return [SpreeEasyPost::TrackerEvent, nil] nil when the payload is not a
# tracker update or carries no tracking code to match on
def self.from_webhook(payload)
- # A webhook body is untrusted input we only ever read, so it is converted
- # wholesale rather than declared field by field — permitting it would
- # imply the values reach a model, and they do not.
- payload = payload.respond_to?(:to_unsafe_h) ? payload.to_unsafe_h : payload
+ # Always a plain Hash: the integration hands over what the SDK's
+ # signature validation parsed from the raw body.
payload = payload.to_h.deep_stringify_keys
return unless payload['description'].to_s.start_with?('tracker.')
tracker = payload['result'] || {}
- tracker = tracker.respond_to?(:to_unsafe_h) ? tracker.to_unsafe_h.deep_stringify_keys : tracker
tracking_code = tracker['tracking_code']
return if tracking_code.blank?
@@ -57,6 +54,20 @@ module SpreeEasyPost
)
end
+ # The shape {Spree::Fulfillments::UpdateTracking} takes, plus the
+ # tracking code the endpoint matches the fulfillment on.
+ #
+ # @return [Hash]
+ def to_update_tracking_arguments
+ {
+ tracking_code: tracking_code,
+ tracking_status: status,
+ estimated_delivery_at: estimated_delivery_at,
+ delivered_at: delivered_at,
+ details: details
+ }
+ end
+
# The scan that actually recorded delivery, which is earlier than the
# webhook and is what a return window has to run from.
def self.delivery_time(tracker)
diff --git a/spree/providers/easypost/lib/spree_easypost/engine.rb b/spree/providers/easypost/lib/spree_easypost/engine.rb
index b5843c95a5..b290bad910 100644
--- a/spree/providers/easypost/lib/spree_easypost/engine.rb
+++ b/spree/providers/easypost/lib/spree_easypost/engine.rb
@@ -13,19 +13,6 @@ module SpreeEasyPost
end
end
- # The gem ships one route (the tracker webhook), so it is appended rather
- # than asking hosts to mount an engine for a single endpoint.
- initializer 'spree_easypost.routes' do |app|
- app.routes.append do
- # Routed to the class rather than a 'spree_easypost/webhooks' string:
- # Rails camelizes that to SpreeEasypost, which is not what the gem's
- # module is called (see the inflection above).
- post '/spree_easypost/webhooks',
- to: SpreeEasyPost::WebhooksController.action(:create),
- as: :spree_easypost_webhooks
- end
- end
-
config.after_initialize do
Spree.integrations << 'SpreeEasyPost::Integration'
Spree.delivery_rate_providers << SpreeEasyPost::DeliveryRateProvider
diff --git a/spree/providers/easypost/spec/models/spree_easypost/tracker_event_spec.rb b/spree/providers/easypost/spec/models/spree_easypost/tracker_event_spec.rb
index a8027461c2..d02b36bc04 100644
--- a/spree/providers/easypost/spec/models/spree_easypost/tracker_event_spec.rb
+++ b/spree/providers/easypost/spec/models/spree_easypost/tracker_event_spec.rb
@@ -84,6 +84,15 @@ RSpec.describe SpreeEasyPost::TrackerEvent do
end
end
+ it 'translates into the update-tracking argument shape' do
+ arguments = described_class.from_webhook(webhook(status: 'in_transit')).to_update_tracking_arguments
+
+ expect(arguments).to include(tracking_code: 'EZ1000000001', tracking_status: 'in_transit')
+ expect(arguments.keys).to contain_exactly(
+ :tracking_code, :tracking_status, :estimated_delivery_at, :delivered_at, :details
+ )
+ end
+
it 'keeps the carrier detail worth showing an admin' do
event = described_class.from_webhook(
webhook(status: 'failure', 'status_detail' => 'address_incorrect')
diff --git a/spree/providers/easypost/spec/requests/spree_easypost/fulfillment_webhooks_spec.rb b/spree/providers/easypost/spec/requests/spree_easypost/fulfillment_webhooks_spec.rb
new file mode 100644
index 0000000000..b4a34e308e
--- /dev/null
+++ b/spree/providers/easypost/spec/requests/spree_easypost/fulfillment_webhooks_spec.rb
@@ -0,0 +1,137 @@
+require 'spec_helper'
+
+# Exercises the unified carrier webhook endpoint end to end with EasyPost as
+# the provider: signed HTTP in, integration verifies and translates, core
+# workflow records the update. Signatures here are real HMACs, not stubs —
+# the verification IS the subject.
+RSpec.describe 'EasyPost fulfillment webhooks', type: :request do
+ let(:store) { @default_store }
+ let(:webhook_secret) { 'whsec_test_secret' }
+
+ # Activation verifies connectivity against EasyPost for real; that network
+ # call is not this spec's subject.
+ before { allow_any_instance_of(SpreeEasyPost::Integration).to receive(:can_connect?).and_return(true) }
+
+ let!(:integration) do
+ SpreeEasyPost::Integration.create!(
+ store: store,
+ active: true,
+ preferences: { api_key: 'EZTK-test', webhook_secret: webhook_secret }
+ )
+ end
+
+ let(:order) { create(:order_ready_to_ship, store: store) }
+ let(:fulfillment) { order.fulfillments.first }
+
+ before do
+ Spree.fulfillment_fulfill_workflow.call(fulfillment: fulfillment)
+ fulfillment.reload.update!(tracking: 'EZ1000000001')
+ host! store.url
+ end
+
+ def sign(body, secret: webhook_secret)
+ normalized = secret.unicode_normalize(:nfkd).encode('utf-8')
+ "hmac-sha256-hex=#{OpenSSL::HMAC.hexdigest('sha256', normalized, body)}"
+ end
+
+ def post_tracker(status:, tracking_code: 'EZ1000000001', secret: webhook_secret, **result)
+ body = {
+ description: 'tracker.updated',
+ result: { object: 'Tracker', tracking_code: tracking_code, status: status, carrier: 'USPS' }.merge(result)
+ }.to_json
+
+ post "/api/v3/webhooks/fulfillments/#{integration.prefixed_id}",
+ params: body,
+ headers: { 'CONTENT_TYPE' => 'application/json', 'X-Hmac-Signature' => sign(body, secret: secret) }
+ end
+
+ it 'records the carrier update on the fulfillment' do
+ post_tracker(status: 'out_for_delivery')
+
+ expect(response).to have_http_status(:ok)
+ expect(fulfillment.reload.tracking_status).to eq('out_for_delivery')
+ end
+
+ it 'confirms receipt when the carrier reports delivery' do
+ post_tracker(
+ status: 'delivered',
+ tracking_details: [{ status: 'delivered', datetime: '2026-08-13T14:20:00Z' }]
+ )
+
+ expect(fulfillment.reload).to be_delivered
+ expect(fulfillment.delivered_at).to eq(Time.utc(2026, 8, 13, 14, 20))
+ end
+
+ it 'records a bounce without moving the fulfillment backwards' do
+ post_tracker(status: 'return_to_sender')
+
+ expect(fulfillment.reload.tracking_status).to eq('return_to_sender')
+ expect(fulfillment).to be_fulfilled
+ end
+
+ describe 'signature verification' do
+ it 'refuses a wrong signature without touching anything' do
+ post_tracker(status: 'delivered', secret: 'not-the-secret')
+
+ expect(response).to have_http_status(:unauthorized)
+ expect(fulfillment.reload.tracking_status).to be_nil
+ end
+
+ it 'refuses an unsigned request' do
+ body = { description: 'tracker.updated', result: { tracking_code: 'EZ1000000001', status: 'delivered' } }.to_json
+
+ post "/api/v3/webhooks/fulfillments/#{integration.prefixed_id}",
+ params: body, headers: { 'CONTENT_TYPE' => 'application/json' }
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+
+ # A merchant who never configured the secret gets a closed endpoint, not
+ # an open one — an unauthenticated delivery report would start the return
+ # window and the EU withdrawal clock.
+ it 'refuses everything while no secret is configured' do
+ integration.update!(preferences: integration.preferences.merge(webhook_secret: nil))
+
+ post_tracker(status: 'delivered', secret: 'anything')
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+
+ describe 'payloads it acknowledges without acting' do
+ it 'accepts an unknown tracking code' do
+ expect {
+ post_tracker(status: 'delivered', tracking_code: 'EZ_NOT_OURS')
+ }.not_to change { fulfillment.reload.status }
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ it 'accepts a non-tracker event' do
+ body = { description: 'batch.created', result: {} }.to_json
+
+ post "/api/v3/webhooks/fulfillments/#{integration.prefixed_id}",
+ params: body,
+ headers: { 'CONTENT_TYPE' => 'application/json', 'X-Hmac-Signature' => sign(body) }
+
+ expect(response).to have_http_status(:ok)
+ end
+ end
+
+ it 'answers 404 for an unknown integration' do
+ body = { description: 'tracker.updated', result: {} }.to_json
+
+ post '/api/v3/webhooks/fulfillments/int_doesnotexist',
+ params: body, headers: { 'CONTENT_TYPE' => 'application/json' }
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it 'ignores an inactive integration' do
+ integration.update!(active: false)
+
+ post_tracker(status: 'delivered')
+
+ expect(response).to have_http_status(:not_found)
+ end
+end
diff --git a/spree/providers/easypost/spec/requests/spree_easypost/webhooks_spec.rb b/spree/providers/easypost/spec/requests/spree_easypost/webhooks_spec.rb
deleted file mode 100644
index 5c7bb9cc04..0000000000
--- a/spree/providers/easypost/spec/requests/spree_easypost/webhooks_spec.rb
+++ /dev/null
@@ -1,75 +0,0 @@
-require 'spec_helper'
-
-# Exercises the whole path a carrier update travels: HTTP in, tracker parsed,
-# core workflow run, fulfillment updated. The pieces are unit-tested
-# separately; this is here because the wiring between them is what breaks.
-RSpec.describe 'EasyPost tracker webhooks', type: :request do
- let(:store) { @default_store }
- let(:order) { create(:order_ready_to_ship, store: store) }
- let(:fulfillment) { order.fulfillments.first }
-
- def post_tracker(status:, tracking_code:, **result)
- post '/spree_easypost/webhooks', params: {
- description: 'tracker.updated',
- result: { object: 'Tracker', tracking_code: tracking_code, status: status, carrier: 'USPS' }.merge(result)
- }, as: :json
- end
-
- before do
- Spree.fulfillment_fulfill_workflow.call(fulfillment: fulfillment)
- fulfillment.reload.update!(tracking: 'EZ1000000001')
- end
-
- it 'records the carrier update on the fulfillment' do
- post_tracker(status: 'out_for_delivery', tracking_code: 'EZ1000000001')
-
- expect(response).to have_http_status(:ok)
- expect(fulfillment.reload.tracking_status).to eq('out_for_delivery')
- end
-
- it 'confirms receipt when the carrier reports delivery' do
- post_tracker(
- status: 'delivered',
- tracking_code: 'EZ1000000001',
- tracking_details: [{ status: 'delivered', datetime: '2026-08-13T14:20:00Z' }]
- )
-
- expect(fulfillment.reload).to be_delivered
- expect(fulfillment.delivered_at).to eq(Time.utc(2026, 8, 13, 14, 20))
- end
-
- # The whole point of the second axis: a bounced parcel is still a parcel the
- # merchant handed over.
- it 'records a bounce without moving the fulfillment backwards' do
- post_tracker(status: 'return_to_sender', tracking_code: 'EZ1000000001')
-
- expect(fulfillment.reload.tracking_status).to eq('return_to_sender')
- expect(fulfillment).to be_fulfilled
- end
-
- describe 'payloads it cannot act on' do
- it 'accepts an unknown tracking code without changing anything' do
- expect {
- post_tracker(status: 'delivered', tracking_code: 'EZ_NOT_OURS')
- }.not_to change { fulfillment.reload.status }
-
- expect(response).to have_http_status(:ok)
- end
-
- it 'accepts a webhook that is not a tracker update' do
- post '/spree_easypost/webhooks', params: { description: 'batch.created', result: {} }, as: :json
-
- expect(response).to have_http_status(:ok)
- end
-
- # Answering anything else would make EasyPost retry a payload that will
- # never succeed.
- it 'still answers 200 when the update itself fails' do
- allow(Spree.fulfillment_update_tracking_workflow).to receive(:call).and_raise('boom')
-
- post_tracker(status: 'in_transit', tracking_code: 'EZ1000000001')
-
- expect(response).to have_http_status(:ok)
- end
- end
-end