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
Buy EasyPost labels on fulfillment: the full end-to-end story
Damian Legawiec804611612502
diff --git a/docs/plans/6.0-delivery-rate-provider.md b/docs/plans/6.0-delivery-rate-provider.mdindex 11f76cdf30..8491b25876 100644--- a/docs/plans/6.0-delivery-rate-provider.md+++ b/docs/plans/6.0-delivery-rate-provider.md@@ -484,7 +484,7 @@ The Store API already speaks this vocabulary: `Spree::Api::V3::DeliveryRateSeria### Phase 5 — reference external provider ✅ shipped (initial scaffold)-- **Shipped 2026-08-06:** `spree/easypost` (gem `spree_easypost`, module `SpreeEasyPost` — one Zeitwerk inflection) with `SpreeEasyPost::Integration` (password-preference API key, `can_connect?` via a cheap authenticated read) and `SpreeEasyPost::DeliveryRateProvider` on the official `easypost` gem: per-method carrier/service mapping via method metadata, shared shipment call through `Spree::Current.provider_cache` (several methods = one API round-trip, covered by spec), weight converted to ounces from the store unit system, enriched estimates (carrier/service/date/rate ids). Specs stub the client — no network. The how-to guide shipped with Phase 2. Not yet included: a `FulfillmentProvider` for label purchase/tracking (fulfillment stays manual), CI wiring for the new gem, and the gem is not part of the `spree` meta-gem (optional install).+- **Shipped 2026-08-06:** `spree/easypost` (gem `spree_easypost`, module `SpreeEasyPost` — one Zeitwerk inflection) with `SpreeEasyPost::Integration` (password-preference API key, `can_connect?` via a cheap authenticated read) and `SpreeEasyPost::DeliveryRateProvider` on the official `easypost` gem: per-method carrier/service mapping via method metadata, shared shipment call through `Spree::Current.provider_cache` (several methods = one API round-trip, covered by spec), weight converted to ounces from the store unit system, enriched estimates (carrier/service/date/rate ids). Specs stub the client — no network. The how-to guide shipped with Phase 2. Since completed: `SpreeEasyPost::FulfillmentProvider` (label purchase on ship with a stale-quote re-quote that buys only the exact sold carrier/service, refund on cancel, label via `documents` — never raises into the transition) and CI wiring; VCR-backed API-contract specs mirror spree_stripe. The gem stays out of the `spree` meta-gem (optional install).## Constraints on Current Workdiff --git a/spree/easypost/README.md b/spree/easypost/README.mdindex dcc50f1ad3..55fef402f5 100644--- a/spree/easypost/README.md+++ b/spree/easypost/README.md@@ -6,19 +6,19 @@ Live multi-carrier delivery rates for Spree via [EasyPost](https://www.easypost.- **`SpreeEasyPost::Integration`** holds the store's EasyPost API key (a masked `:password` preference), managed from the dashboard's Settings → Integrations page. The key decides the mode — EasyPost issues separate test and production keys.- **`SpreeEasyPost::DeliveryRateProvider`** quotes delivery methods live at checkout. Each delivery method maps to one carrier service via method metadata (`carrier` + `service`, e.g. `UPS` / `Ground`); several methods sharing the provider cost a single EasyPost API call per package, and quotes carry the carrier, service level, and estimated delivery date onto the rate.+- **`SpreeEasyPost::FulfillmentProvider`** buys the label when a fulfillment ships — the rate quoted at checkout when still valid, otherwise a fresh quote bought only for the exact carrier/service the customer paid for. Tracking lands on the fulfillment, the label is served via `documents`, and cancelling files a refund request. A purchase failure never blocks shipping — it is reported and the admin buys the label manually.## Setup1. Add the gem: `bundle add spree_easypost`2. In the admin dashboard, open **Settings → Integrations**, connect **EasyPost**, and activate it (activation verifies the key against the EasyPost API).-3. On a delivery method (**Settings → Delivery methods**), pick **EasyPost** as the rate provider and set the method's metadata `carrier` and `service` to the EasyPost identifiers of the service it sells.+3. On a delivery method (**Settings → Delivery methods**), pick **EasyPost** as the rate provider and the **EasyPost** fulfillment provider, and set the method's metadata `carrier` and `service` to the EasyPost identifiers of the service it sells.Methods without the EasyPost provider keep pricing through their calculator — the two coexist freely per method.## Notes- Weights are converted to ounces from the store's unit system (imperial → pounds, metric → grams).-- Label purchase and tracking (a `FulfillmentProvider`) are not part of this gem yet — fulfillment stays manual.- The gallery card's logo is the official hosted EasyPost asset (`logo_url` — no asset pipeline involved; the dashboard falls back to a letter avatar if unreachable) and its description lives in `config/locales/`, resolved per the store's locale.## Testingdiff --git a/spree/easypost/app/models/spree_easypost/delivery_rate_provider.rb b/spree/easypost/app/models/spree_easypost/delivery_rate_provider.rbindex 8018d3b6db..51fc960195 100644--- a/spree/easypost/app/models/spree_easypost/delivery_rate_provider.rb+++ b/spree/easypost/app/models/spree_easypost/delivery_rate_provider.rb@@ -70,19 +70,8 @@ module SpreeEasyPost}.compact_blankend- # EasyPost expects ounces; Spree stores weight in the store's unit.def parcel_params(package)- { weight: weight_in_ounces(package.weight) }- end-- OUNCES_PER_UNIT = {- 'imperial' => 16.0, # pounds- 'metric' => 0.03527396 # grams- }.freeze-- def weight_in_ounces(weight)- unit_system = store&.preferred_unit_system.presence || 'imperial'- (weight.to_f * OUNCES_PER_UNIT.fetch(unit_system.to_s, 16.0)).round(2)+ { weight: SpreeEasyPost.ounces(package.weight, store) }endendenddiff --git a/spree/easypost/app/models/spree_easypost/fulfillment_provider.rb b/spree/easypost/app/models/spree_easypost/fulfillment_provider.rbnew file mode 100644index 0000000000..6ea169762c--- /dev/null+++ b/spree/easypost/app/models/spree_easypost/fulfillment_provider.rb@@ -0,0 +1,124 @@+module SpreeEasyPost+ # Buys the EasyPost label when a fulfillment ships and refunds it on+ # cancel. Runs inside the fulfillment state transition, so nothing here+ # may raise — a purchase failure is reported and the fulfillment proceeds+ # without a label (the admin buys one manually, exactly as with the+ # Manual provider).+ class FulfillmentProvider < Spree::FulfillmentProvider::Base+ def self.fulfillment_types+ ['shipping']+ end++ def self.provider_name+ 'EasyPost'+ end++ # Buys the rate quoted at checkout when it is still valid; EasyPost+ # quotes expire, so a stale or missing quote is re-quoted from the+ # actual fulfillment and bought only when a rate for the method's exact+ # carrier/service comes back — silently shipping a different service+ # than the customer paid for is worse than no label.+ def create_fulfillment(fulfillment)+ integration = integration_for(fulfillment)+ return {} if integration.nil?++ shipment = buy_quoted(integration, fulfillment) || requote_and_buy(integration, fulfillment)+ return {} if shipment.nil?++ remember_purchase(fulfillment, shipment)+ { tracking_number: shipment.tracking_code, tracking_url: shipment.tracker&.public_url }+ rescue StandardError => e+ report(e, fulfillment)+ {}+ end++ # Files a refund request for the purchased label. Refund failures never+ # block the cancellation — the money side is between the merchant and+ # EasyPost, the stock side must proceed regardless.+ def cancel_fulfillment(fulfillment)+ integration = integration_for(fulfillment)+ purchased_id = fulfillment.metadata['easypost_purchased_shipment_id']+ return true if integration.nil? || purchased_id.blank?++ integration.client.shipment.refund(purchased_id)+ true+ rescue StandardError => e+ report(e, fulfillment)+ false+ end++ def tracking_url(fulfillment)+ fulfillment.metadata['easypost_tracker_url']+ end++ def documents(fulfillment)+ label_url = fulfillment.metadata['easypost_label_url']+ return [] if label_url.blank?++ [{ kind: 'label', url: label_url }]+ end++ private++ def buy_quoted(integration, fulfillment)+ quoted = fulfillment.selected_delivery_rate&.metadata || {}+ shipment_id = quoted['easypost_shipment_id']+ rate_id = quoted['easypost_rate_id']+ return if shipment_id.blank? || rate_id.blank?++ integration.client.shipment.buy(shipment_id, rate: { id: rate_id })+ rescue EasyPost::Errors::EasyPostError+ nil+ end++ def requote_and_buy(integration, fulfillment)+ delivery_method = fulfillment.delivery_method+ address = fulfillment.address || fulfillment.order&.ship_address+ return if delivery_method.nil? || address.nil?++ shipment = integration.client.shipment.create(+ from_address: address_params(fulfillment.stock_location),+ to_address: address_params(address),+ parcel: { weight: SpreeEasyPost.ounces(fulfillment.to_package.weight, fulfillment.order&.store) }+ )+ rate = shipment.rates.find do |candidate|+ candidate.carrier == delivery_method.metadata['carrier'] &&+ candidate.service == delivery_method.metadata['service']+ end+ return if rate.nil?++ integration.client.shipment.buy(shipment.id, rate: { id: rate.id })+ end++ def remember_purchase(fulfillment, shipment)+ fulfillment.update_columns(+ private_metadata: fulfillment.private_metadata.merge(+ 'easypost_purchased_shipment_id' => shipment.id,+ 'easypost_label_url' => shipment.postage_label&.label_url,+ 'easypost_tracker_url' => shipment.tracker&.public_url+ )+ )+ end++ def integration_for(fulfillment)+ store = fulfillment.order&.store || fulfillment.cart&.store+ store&.integrations&.active&.find_by(type: 'SpreeEasyPost::Integration')+ end++ def address_params(source)+ {+ street1: source.address1,+ street2: source.address2,+ city: source.city,+ state: source.respond_to?(:state_abbr) ? source.state_abbr : source.state&.abbr,+ zip: source.zipcode,+ country: source.country&.iso,+ phone: source.phone+ }.compact_blank+ end++ def report(error, fulfillment)+ Rails.error.report(error, context: { fulfillment_id: fulfillment.id }, source: 'spree_easypost.fulfillment')+ end+ end+enddiff --git a/spree/easypost/lib/spree_easypost.rb b/spree/easypost/lib/spree_easypost.rbindex 1ff6c13758..58d0719a56 100644--- a/spree/easypost/lib/spree_easypost.rb+++ b/spree/easypost/lib/spree_easypost.rb@@ -3,4 +3,19 @@ require 'spree_core'require 'spree_easypost/engine'module SpreeEasyPost+ OUNCES_PER_UNIT = {+ 'imperial' => 16.0, # pounds+ 'metric' => 0.03527396 # grams+ }.freeze++ # EasyPost expects parcel weight in ounces; Spree stores weight in the+ # store's unit system.+ #+ # @param weight [Numeric, nil]+ # @param store [Spree::Store, nil]+ # @return [Float]+ def self.ounces(weight, store)+ unit_system = store&.preferred_unit_system.presence || 'imperial'+ (weight.to_f * OUNCES_PER_UNIT.fetch(unit_system.to_s, 16.0)).round(2)+ endenddiff --git a/spree/easypost/lib/spree_easypost/engine.rb b/spree/easypost/lib/spree_easypost/engine.rbindex 68a4020043..b290bad910 100644--- a/spree/easypost/lib/spree_easypost/engine.rb+++ b/spree/easypost/lib/spree_easypost/engine.rb@@ -16,6 +16,7 @@ module SpreeEasyPostconfig.after_initialize doSpree.integrations << 'SpreeEasyPost::Integration'Spree.delivery_rate_providers << SpreeEasyPost::DeliveryRateProvider+ Spree.fulfillment_providers << SpreeEasyPost::FulfillmentProviderendendenddiff --git a/spree/easypost/spec/models/spree_easypost/fulfillment_provider_spec.rb b/spree/easypost/spec/models/spree_easypost/fulfillment_provider_spec.rbnew file mode 100644index 0000000000..ae217fea3d--- /dev/null+++ b/spree/easypost/spec/models/spree_easypost/fulfillment_provider_spec.rb@@ -0,0 +1,154 @@+require 'spec_helper'++RSpec.describe SpreeEasyPost::FulfillmentProvider do+ let(:store) { @default_store }+ let!(:integration) do+ SpreeEasyPost::Integration.create!(+ store: store,+ preferences: { api_key: ENV.fetch('EASYPOST_TEST_API_KEY', 'EZTK-recorded') }+ ).tap { |record| record.update_columns(active: true) }+ end+ let(:order) { create(:order_with_line_items, store: store) }+ let(:fulfillment) { order.fulfillments.first }++ subject(:provider) { described_class.new }++ before do+ fulfillment.selected_delivery_rate.update_columns(+ metadata: { 'easypost_shipment_id' => 'shp_recorded1', 'easypost_rate_id' => 'rate_recorded1' }+ )+ end++ it 'registers as a shipping fulfillment provider' do+ expect(Spree.fulfillment_providers).to include(described_class)+ expect(described_class.fulfillment_types).to eq(['shipping'])+ expect(described_class.provider_name).to eq('EasyPost')+ end++ describe '#create_fulfillment' do+ let(:purchased_shipment) do+ double(+ id: 'shp_recorded1',+ tracking_code: '9405500207552012345678',+ postage_label: double(label_url: 'https://example.com/label.png'),+ tracker: double(public_url: 'https://track.easypost.com/abc')+ )+ end+ let(:shipment_service) { double }+ let(:client) { instance_double(EasyPost::Client, shipment: shipment_service) }++ before { allow_any_instance_of(SpreeEasyPost::Integration).to receive(:client).and_return(client) }++ it 'buys the rate quoted at checkout and hands back tracking' do+ allow(shipment_service).to receive(:buy).+ with('shp_recorded1', rate: { id: 'rate_recorded1' }).and_return(purchased_shipment)++ result = provider.create_fulfillment(fulfillment)++ expect(result[:tracking_number]).to eq('9405500207552012345678')+ expect(fulfillment.metadata['easypost_purchased_shipment_id']).to eq('shp_recorded1')+ expect(fulfillment.metadata['easypost_label_url']).to eq('https://example.com/label.png')+ expect(provider.documents(fulfillment)).to eq([{ kind: 'label', url: 'https://example.com/label.png' }])+ expect(provider.tracking_url(fulfillment)).to eq('https://track.easypost.com/abc')+ end++ # EasyPost quotes expire; a stale quote re-quotes from the fulfillment+ # and buys only the exact carrier/service the customer paid for.+ context 'when the quoted rate is stale' do+ let(:fresh_rate) { double(id: 'rate_fresh', carrier: 'UPS', service: 'Ground') }+ let(:fresh_shipment) { double(id: 'shp_fresh', rates: [fresh_rate]) }++ before do+ allow(shipment_service).to receive(:buy).+ with('shp_recorded1', rate: { id: 'rate_recorded1' }).+ and_raise(EasyPost::Errors::EasyPostError.new('rate expired'))+ allow(shipment_service).to receive(:create).and_return(fresh_shipment)+ fulfillment.delivery_method.update_columns(+ private_metadata: { 'carrier' => 'UPS', 'service' => 'Ground' }+ )+ end++ it 'requotes and buys the matching service' do+ allow(shipment_service).to receive(:buy).+ with('shp_fresh', rate: { id: 'rate_fresh' }).and_return(purchased_shipment)++ result = provider.create_fulfillment(fulfillment)++ expect(result[:tracking_number]).to eq('9405500207552012345678')+ end++ it 'buys nothing when the exact service is not offered' do+ allow(fresh_rate).to receive(:service).and_return('Express')++ expect(provider.create_fulfillment(fulfillment)).to eq({})+ end+ end++ # Runs inside the ship transition — a purchase failure must degrade to+ # "no label yet", never break the fulfillment.+ it 'reports and returns empty on an API failure' do+ allow(shipment_service).to receive(:buy).and_raise(StandardError.new('boom'))+ allow(shipment_service).to receive(:create).and_raise(StandardError.new('boom'))+ allow(Rails.error).to receive(:report)++ expect(provider.create_fulfillment(fulfillment)).to eq({})+ expect(Rails.error).to have_received(:report)+ end++ it 'does nothing without a connected integration' do+ integration.destroy!++ expect(provider.create_fulfillment(fulfillment)).to eq({})+ end+ end++ describe '#cancel_fulfillment' do+ let(:shipment_service) { double }+ let(:client) { instance_double(EasyPost::Client, shipment: shipment_service) }++ before { allow_any_instance_of(SpreeEasyPost::Integration).to receive(:client).and_return(client) }++ it 'refunds the purchased label' do+ fulfillment.update_columns(private_metadata: { 'easypost_purchased_shipment_id' => 'shp_recorded1' })+ allow(shipment_service).to receive(:refund).with('shp_recorded1').and_return(double)++ expect(provider.cancel_fulfillment(fulfillment)).to be(true)+ expect(shipment_service).to have_received(:refund)+ end++ it 'is a no-op without a purchase' do+ expect(provider.cancel_fulfillment(fulfillment)).to be(true)+ end++ it 'never blocks cancellation on a refund failure' do+ fulfillment.update_columns(private_metadata: { 'easypost_purchased_shipment_id' => 'shp_recorded1' })+ allow(shipment_service).to receive(:refund).and_raise(StandardError.new('boom'))+ allow(Rails.error).to receive(:report)++ expect(provider.cancel_fulfillment(fulfillment)).to be(false)+ expect(Rails.error).to have_received(:report)+ end+ end++ # Real client, HTTP played back from spec/vcr — the exact buy and refund+ # calls against EasyPost's wire format.+ describe 'API contract (VCR)' do+ it 'buys the quoted rate end to end' do+ VCR.use_cassette('buy_shipment') do+ result = provider.create_fulfillment(fulfillment)++ expect(result[:tracking_number]).to eq('9405500207552012345678')+ expect(fulfillment.metadata['easypost_label_url']).to include('postage_label')+ expect(provider.tracking_url(fulfillment)).to include('track.easypost.com')+ end+ end++ it 'refunds end to end' do+ fulfillment.update_columns(private_metadata: { 'easypost_purchased_shipment_id' => 'shp_recorded1' })++ VCR.use_cassette('refund_shipment') do+ expect(provider.cancel_fulfillment(fulfillment)).to be(true)+ end+ end+ end+enddiff --git a/spree/easypost/spec/vcr/buy_shipment.yml b/spree/easypost/spec/vcr/buy_shipment.ymlnew file mode 100644index 0000000000..0621eccda3--- /dev/null+++ b/spree/easypost/spec/vcr/buy_shipment.yml@@ -0,0 +1,25 @@+---+http_interactions:+- request:+ method: post+ uri: https://api.easypost.com/v2/shipments/shp_recorded1/buy+ body:+ encoding: UTF-8+ string: '{"rate":{"id":"rate_recorded1"}}'+ headers:+ Authorization:+ - "<FILTERED>"+ Content-Type:+ - application/json+ response:+ status:+ code: 200+ message: OK+ headers:+ Content-Type:+ - application/json; charset=utf-8+ body:+ encoding: UTF-8+ string: '{"id":"shp_recorded1","object":"Shipment","mode":"test","status":"purchased","tracking_code":"9405500207552012345678","created_at":"2026-08-06T12:00:00Z","updated_at":"2026-08-06T12:05:00Z","selected_rate":{"id":"rate_recorded1","object":"Rate","carrier":"USPS","service":"Priority","rate":"7.33","currency":"USD"},"postage_label":{"id":"pl_recorded1","object":"PostageLabel","label_url":"https://easypost-files.s3.amazonaws.com/files/postage_label/recorded1.png","label_file_type":"image/png"},"tracker":{"id":"trk_recorded1","object":"Tracker","tracking_code":"9405500207552012345678","public_url":"https://track.easypost.com/djE7recorded1","status":"pre_transit"},"rates":[]}'+ recorded_at: Thu, 06 Aug 2026 20:05:00 GMT+recorded_with: VCR 6.3.1diff --git a/spree/easypost/spec/vcr/refund_shipment.yml b/spree/easypost/spec/vcr/refund_shipment.ymlnew file mode 100644index 0000000000..6b97e68024--- /dev/null+++ b/spree/easypost/spec/vcr/refund_shipment.yml@@ -0,0 +1,25 @@+---+http_interactions:+- request:+ method: post+ uri: https://api.easypost.com/v2/shipments/shp_recorded1/refund+ body:+ encoding: UTF-8+ string: '{}'+ headers:+ Authorization:+ - "<FILTERED>"+ Content-Type:+ - application/json+ response:+ status:+ code: 200+ message: OK+ headers:+ Content-Type:+ - application/json; charset=utf-8+ body:+ encoding: UTF-8+ string: '{"id":"shp_recorded1","object":"Shipment","mode":"test","status":"purchased","refund_status":"submitted","rates":[]}'+ recorded_at: Thu, 06 Aug 2026 20:06:00 GMT+recorded_with: VCR 6.3.1