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
Add spree_easypost: the reference EasyPost delivery rate provider gem
Damian Legawiec5d8607b5625f
diff --git a/docs/plans/6.0-delivery-rate-provider.md b/docs/plans/6.0-delivery-rate-provider.mdindex 7616962953..11f76cdf30 100644--- a/docs/plans/6.0-delivery-rate-provider.md+++ b/docs/plans/6.0-delivery-rate-provider.md@@ -1,6 +1,6 @@# Delivery Rate Provider Interface-**Status:** Phases 1–4 shipped (see "Implementation status"); Phase 5 (the EasyPost gem) pending. Reference aggregator: **EasyPost** (decisions.md 2026-08-06 — Shippo pick reversed same day: BYOCA fit for larger merchants + the only actively maintained official Ruby SDK)+**Status:** Phases 1–5 shipped (see "Implementation status"; Phase 5 as an initial scaffold — no FulfillmentProvider/CI wiring yet). Reference aggregator: **EasyPost** (decisions.md 2026-08-06 — Shippo pick reversed same day: BYOCA fit for larger merchants + the only actively maintained official Ruby SDK)**Target:** Spree 6.0**Depends on:** Fulfillment & Delivery (6.0-fulfillment-and-delivery.md) for the DeliveryMethod/DeliveryRate rename. Coordinates with: `6.0-multi-vendor-marketplace.md` (vendor-scoped method filtering — this plan owns the filter), `6.0-cart-order-split.md` (where estimation is invoked pre-completion), `5.6-6.0-single-store-promotions-payment-methods.md` (single-store pattern reused for `store_id`)**Author:** Damian + Claude@@ -482,9 +482,9 @@ The Store API already speaks this vocabulary: `Spree::Api::V3::DeliveryRateSeria- Dashboard delivery-method page: provider select + schema-driven calculator preference forms (`PreferencesForm`, per the 2026-07-21 routing-rules pattern), `<Can>`-gated, i18n in all locale files.- The legacy admin's `_calculator_fields.html.erb` and shipping-method form are deleted with `spree/admin` at 6.0 — no work there. (Any 5.x interim wiring may touch them; note the partial is shared with tax rates and promotion actions.)-### Phase 5 — reference external provider+### Phase 5 — reference external provider ✅ shipped (initial scaffold)-- Ship an EasyPost provider gem (decisions.md 2026-08-06, reversal entry) and a how-to guide, mirroring the custom-search-provider doc — built on the official `easypost` gem. The EasyPost snippets elsewhere in this document are now the pick, not just illustration.+- **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).## Constraints on Current Workdiff --git a/spree/easypost/Gemfile b/spree/easypost/Gemfilenew file mode 100644index 0000000000..bcb6bab621--- /dev/null+++ b/spree/easypost/Gemfile@@ -0,0 +1,5 @@+eval_gemfile('../common_spree_dependencies.rb')++gem 'spree', path: '../'++gemspecdiff --git a/spree/easypost/README.md b/spree/easypost/README.mdnew file mode 100644index 0000000000..5675a5f241--- /dev/null+++ b/spree/easypost/README.md@@ -0,0 +1,32 @@+# spree_easypost++Live multi-carrier delivery rates for Spree via [EasyPost](https://www.easypost.com) — the reference implementation of the `Spree::DeliveryRateProvider` interface, built on the official [`easypost`](https://github.com/EasyPost/easypost-ruby) Ruby SDK.++## What it does++- **`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.++## Setup++1. 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.++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.++## Testing++```bash+cd spree/easypost+bundle install+bundle exec rake test_app+bundle exec rspec+```++Specs stub the EasyPost client — no network calls, no API key needed.diff --git a/spree/easypost/Rakefile b/spree/easypost/Rakefilenew file mode 100644index 0000000000..92068acf81--- /dev/null+++ b/spree/easypost/Rakefile@@ -0,0 +1,15 @@+require 'rubygems'+require 'rake'+require 'rake/testtask'+require 'rspec/core/rake_task'+require 'spree/testing_support/common_rake'++RSpec::Core::RakeTask.new++task default: :spec++desc "Generates a dummy app for testing"+task :test_app do+ ENV['LIB_NAME'] = 'spree_easypost'+ Rake::Task['common:test_app'].invoke+enddiff --git a/spree/easypost/app/models/spree_easypost/delivery_rate_provider.rb b/spree/easypost/app/models/spree_easypost/delivery_rate_provider.rbnew file mode 100644index 0000000000..d8e38ea44b--- /dev/null+++ b/spree/easypost/app/models/spree_easypost/delivery_rate_provider.rb@@ -0,0 +1,79 @@+module SpreeEasyPost+ # Quotes a delivery method from EasyPost. Each method maps to one carrier+ # service (metadata: `carrier` + `service`, e.g. UPS/Ground) — "Ground" and+ # "Express" are two DeliveryMethods sharing this provider, and the shared+ # shipment call below means quoting both costs one API round-trip.+ class DeliveryRateProvider < Spree::DeliveryRateProvider::Base+ def self.integration_class+ 'SpreeEasyPost::Integration'+ end++ # @param package [Spree::Stock::Package]+ # @return [Spree::DeliveryRateProvider::Estimate, nil]+ def estimate(package)+ return if integration.nil?+ return if package.order.ship_address.nil?++ rate = matching_rate(package)+ return if rate.nil?++ Spree::DeliveryRateProvider::Estimate.new(+ cost: rate.rate,+ carrier: rate.carrier,+ service_level: rate.service,+ estimated_delivery_date: rate.delivery_date,+ metadata: { 'easypost_rate_id' => rate.id, 'easypost_shipment_id' => rate.shipment_id }+ )+ end++ private++ def matching_rate(package)+ carrier = delivery_method.metadata['carrier']+ service = delivery_method.metadata['service']+ return if carrier.blank? || service.blank?++ easypost_shipment(package).rates.find do |rate|+ rate.carrier == carrier && rate.service == service+ end+ end++ # One shipment-create returns rates for every carrier and service, so all+ # delivery methods sharing this provider within a request reuse it.+ def easypost_shipment(package)+ cache_key = [:easypost_shipment, store.id, package.stock_location.id, package.order.id]+ Spree::Current.provider_cache[cache_key] ||= integration.client.shipment.create(+ from_address: address_params(package.stock_location),+ to_address: address_params(package.order.ship_address),+ parcel: parcel_params(package)+ )+ 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++ # 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)+ end+ end+enddiff --git a/spree/easypost/app/models/spree_easypost/integration.rb b/spree/easypost/app/models/spree_easypost/integration.rbnew file mode 100644index 0000000000..af5d0c50ec--- /dev/null+++ b/spree/easypost/app/models/spree_easypost/integration.rb@@ -0,0 +1,30 @@+module SpreeEasyPost+ # Per-store EasyPost credentials. The API key decides the mode — EasyPost+ # issues separate test and production keys, so there is no mode toggle.+ class Integration < Spree::Integration+ preference :api_key, :password++ def self.integration_group+ 'shipping'+ end++ def self.integration_name+ 'EasyPost'+ end++ # A cheap authenticated read: fails with 401 on a bad key without+ # creating anything on the account.+ def can_connect?+ client.carrier_account.all+ true+ rescue EasyPost::Errors::EasyPostError => e+ self.connection_error_message = e.message+ false+ end++ # @return [EasyPost::Client]+ def client+ @client ||= EasyPost::Client.new(api_key: preferred_api_key)+ end+ end+enddiff --git a/spree/easypost/lib/spree_easypost.rb b/spree/easypost/lib/spree_easypost.rbnew file mode 100644index 0000000000..1ff6c13758--- /dev/null+++ b/spree/easypost/lib/spree_easypost.rb@@ -0,0 +1,6 @@+require 'easypost'+require 'spree_core'+require 'spree_easypost/engine'++module SpreeEasyPost+enddiff --git a/spree/easypost/lib/spree_easypost/engine.rb b/spree/easypost/lib/spree_easypost/engine.rbnew file mode 100644index 0000000000..68a4020043--- /dev/null+++ b/spree/easypost/lib/spree_easypost/engine.rb@@ -0,0 +1,21 @@+require 'rails/engine'++module SpreeEasyPost+ class Engine < Rails::Engine+ engine_name 'spree_easypost'++ # Gem name and module disagree on word boundaries (spree_easypost →+ # SpreeEasyPost, matching the official EasyPost SDK's casing), so+ # Zeitwerk needs telling once.+ initializer 'spree_easypost.inflections', before: :set_autoload_paths do+ Rails.autoloaders.each do |autoloader|+ autoloader.inflector.inflect('spree_easypost' => 'SpreeEasyPost')+ end+ end++ config.after_initialize do+ Spree.integrations << 'SpreeEasyPost::Integration'+ Spree.delivery_rate_providers << SpreeEasyPost::DeliveryRateProvider+ end+ end+enddiff --git a/spree/easypost/spec/models/spree_easypost/delivery_rate_provider_spec.rb b/spree/easypost/spec/models/spree_easypost/delivery_rate_provider_spec.rbnew file mode 100644index 0000000000..8150ff63eb--- /dev/null+++ b/spree/easypost/spec/models/spree_easypost/delivery_rate_provider_spec.rb@@ -0,0 +1,85 @@+require 'spec_helper'++RSpec.describe SpreeEasyPost::DeliveryRateProvider do+ let(:store) { @default_store }+ # let! — the delivery method's rate_provider validation requires a+ # connected integration to exist at create time.+ let!(:integration) do+ SpreeEasyPost::Integration.new(store: store, active: true, preferences: { api_key: 'EZTK-test' }).tap do |record|+ allow(record).to receive(:can_connect?).and_return(true)+ record.save!+ end+ end+ let(:delivery_method) do+ create(:delivery_method, store: store,+ rate_provider: described_class.to_s,+ metadata: { 'carrier' => 'UPS', 'service' => 'Ground' })+ end+ let(:order) { create(:order_with_line_items, store: store) }+ let(:package) { order.fulfillments.first.to_package }++ subject(:provider) { described_class.new(delivery_method) }++ let(:ground_rate) do+ double(carrier: 'UPS', service: 'Ground', rate: '8.99',+ delivery_date: '2026-08-12', id: 'rate_1', shipment_id: 'shp_1')+ end+ let(:express_rate) do+ double(carrier: 'UPS', service: 'Express', rate: '24.99',+ delivery_date: '2026-08-08', id: 'rate_2', shipment_id: 'shp_1')+ end+ let(:easypost_shipment) { double(rates: [ground_rate, express_rate]) }+ let(:shipment_service) { double(create: easypost_shipment) }+ let(:client) { instance_double(EasyPost::Client, shipment: shipment_service) }++ before do+ allow(integration).to receive(:client).and_return(client)+ allow(provider).to receive(:integration).and_return(integration)+ Spree::Current.reset+ end++ it 'registers itself and declares its integration' do+ expect(Spree.delivery_rate_providers).to include(described_class)+ expect(described_class.integration_class).to eq('SpreeEasyPost::Integration')+ end++ describe '#estimate' do+ it 'quotes the configured carrier service with enriched fields' do+ estimate = provider.estimate(package)++ expect(estimate.cost).to eq(BigDecimal('8.99'))+ expect(estimate.carrier).to eq('UPS')+ expect(estimate.service_level).to eq('Ground')+ expect(estimate.estimated_delivery_date).to eq(Date.new(2026, 8, 12))+ expect(estimate.metadata['easypost_rate_id']).to eq('rate_1')+ end++ it 'suppresses the method when no rate matches the configured service' do+ delivery_method.metadata['service'] = 'Overnight'++ expect(provider.estimate(package)).to be_nil+ end++ it 'suppresses the method when the integration is not connected' do+ allow(provider).to receive(:integration).and_return(nil)++ expect(provider.estimate(package)).to be_nil+ end++ # The whole point of the shared shipment call: several methods quoting+ # through this provider must cost one API round-trip, not one each.+ it 'reuses the shipment across methods within a request' do+ express_method = create(:delivery_method, store: store,+ rate_provider: described_class.to_s,+ metadata: { 'carrier' => 'UPS', 'service' => 'Express' })+ express_provider = described_class.new(express_method)+ allow(express_provider).to receive(:integration).and_return(integration)++ provider.estimate(package)+ express_estimate = express_provider.estimate(package)++ expect(shipment_service).to have_received(:create).once+ expect(express_estimate.cost).to eq(BigDecimal('24.99'))+ end+ end+enddiff --git a/spree/easypost/spec/models/spree_easypost/integration_spec.rb b/spree/easypost/spec/models/spree_easypost/integration_spec.rbnew file mode 100644index 0000000000..f9ba32f535--- /dev/null+++ b/spree/easypost/spec/models/spree_easypost/integration_spec.rb@@ -0,0 +1,48 @@+require 'spec_helper'++RSpec.describe SpreeEasyPost::Integration do+ subject(:integration) do+ described_class.new(store: @default_store, preferences: { api_key: 'EZTK-test' })+ end++ it 'registers as a shipping integration' do+ expect(Spree.integrations).to include('SpreeEasyPost::Integration')+ expect(described_class.integration_group).to eq('shipping')+ expect(described_class.integration_name).to eq('EasyPost')+ # Wire shorthand comes from the outer module — SpreeEasyPost → easy_post.+ expect(described_class.api_type).to eq('easy_post')+ end++ it 'masks the api key as a password preference' do+ expect(described_class.password_preference_keys).to include(:api_key)+ end++ describe '#can_connect?' do+ let(:carrier_account_service) { double(all: []) }+ let(:client) { instance_double(EasyPost::Client, carrier_account: carrier_account_service) }++ before { allow(integration).to receive(:client).and_return(client) }++ it 'is true when an authenticated read succeeds' do+ expect(integration.can_connect?).to be(true)+ end++ it 'captures the vendor message on failure' do+ allow(carrier_account_service).to receive(:all).+ and_raise(EasyPost::Errors::EasyPostError.new('unauthorized'))++ expect(integration.can_connect?).to be(false)+ expect(integration.connection_error_message).to eq('unauthorized')+ end+ end++ describe 'verify before activate' do+ it 'blocks activation when the connection fails' do+ allow(integration).to receive(:can_connect?).and_return(false)+ integration.active = true++ expect(integration).not_to be_valid+ expect(integration.errors[:active]).to be_present+ end+ end+enddiff --git a/spree/easypost/spec/spec_helper.rb b/spree/easypost/spec/spec_helper.rbnew file mode 100644index 0000000000..bf13b5d5d0--- /dev/null+++ b/spree/easypost/spec/spec_helper.rb@@ -0,0 +1,35 @@+ENV['RAILS_ENV'] ||= 'test'++begin+ require File.expand_path('../dummy/config/environment', __FILE__)+rescue LoadError+ puts 'Could not load dummy application. Please ensure you have run `bundle exec rake test_app`'+end++require 'rspec/rails'+require 'database_cleaner/active_record'+require 'ffaker'++require 'spree/testing_support/factories'+require 'spree/testing_support/jobs'+require 'spree/testing_support/store'+require 'spree/testing_support/preferences'+require 'spree/testing_support/rspec_retry_config'++RSpec.configure do |config|+ config.color = true+ config.default_formatter = 'progress'+ config.infer_spec_type_from_file_location!+ config.mock_with :rspec+ config.raise_errors_for_deprecations!+ config.use_transactional_fixtures = true++ config.include FactoryBot::Syntax::Methods++ config.before(:suite) do+ Spree::Events.disable!+ end++ config.order = :random+ Kernel.srand config.seed+enddiff --git a/spree/easypost/spree_easypost.gemspec b/spree/easypost/spree_easypost.gemspecnew file mode 100644index 0000000000..a01bd4f356--- /dev/null+++ b/spree/easypost/spree_easypost.gemspec@@ -0,0 +1,30 @@+# encoding: UTF-8++require_relative '../core/lib/spree/core/version.rb'++Gem::Specification.new do |s|+ s.platform = Gem::Platform::RUBY+ s.name = 'spree_easypost'+ s.version = Spree.version+ s.authors = ['Spark Solutions Sp. z o.o.', 'Vendo Connect Inc.']+ s.email = '[email protected]'+ s.summary = 'EasyPost delivery rates for Spree eCommerce platform'+ s.description = 'Live multi-carrier delivery rates for Spree via EasyPost — the reference DeliveryRateProvider implementation'+ s.homepage = 'https://spreecommerce.org'+ s.license = 'BSD-3-Clause'++ s.metadata = {+ "bug_tracker_uri" => "https://github.com/spree/spree/issues",+ "changelog_uri" => "https://github.com/spree/spree/releases/tag/v#{s.version}",+ "documentation_uri" => "https://docs.spreecommerce.org/",+ "source_code_uri" => "https://github.com/spree/spree/tree/v#{s.version}",+ }++ s.required_ruby_version = '>= 3.2'++ s.files = Dir["{app,config,db,lib,vendor}/**/*", "Rakefile", "README.md"].reject { |f| f.match(/^spec/) && !f.match(/^spec\/fixtures/) }+ s.require_path = 'lib'++ s.add_dependency 'easypost', '~> 7.0'+ s.add_dependency 'spree_core', ">= #{s.version}"+end