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
Added PayPal webhook verification and registration
Łukasz Adamczykf03ea4a51460
diff --git a/spree/providers/paypal/app/jobs/spree_paypal_checkout/base_job.rb b/spree/providers/paypal/app/jobs/spree_paypal_checkout/base_job.rbnew file mode 100644index 0000000000..35d7311b8b--- /dev/null+++ b/spree/providers/paypal/app/jobs/spree_paypal_checkout/base_job.rb@@ -0,0 +1,5 @@+module SpreePaypalCheckout+ class BaseJob < Spree::BaseJob+ queue_as { SpreePaypalCheckout.queue }+ end+enddiff --git a/spree/providers/paypal/app/jobs/spree_paypal_checkout/register_webhook_job.rb b/spree/providers/paypal/app/jobs/spree_paypal_checkout/register_webhook_job.rbnew file mode 100644index 0000000000..89d54b8f74--- /dev/null+++ b/spree/providers/paypal/app/jobs/spree_paypal_checkout/register_webhook_job.rb@@ -0,0 +1,20 @@+module SpreePaypalCheckout+ class RegisterWebhookJob < BaseJob+ # Safe to replay: registration finds the webhook for the URL before+ # creating one.+ retry_on StandardError, wait: :polynomially_longer, attempts: 5+ # Must come after `retry_on StandardError` so DeserializationError lands in discard.+ discard_on ActiveJob::DeserializationError++ def perform(payment_method_id)+ # Locked on load: two saves in a row queue two jobs, and both would+ # otherwise create a webhook for the same URL.+ Spree::PaymentMethod.transaction do+ payment_method = Spree::PaymentMethod.lock.find_by(id: payment_method_id)+ next unless payment_method.is_a?(SpreePaypalCheckout::Gateway)++ payment_method.register_webhook+ end+ end+ end+enddiff --git a/spree/providers/paypal/app/models/spree_paypal_checkout/gateway.rb b/spree/providers/paypal/app/models/spree_paypal_checkout/gateway.rbindex 2d504d21a8..6d3f8a4100 100644--- a/spree/providers/paypal/app/models/spree_paypal_checkout/gateway.rb+++ b/spree/providers/paypal/app/models/spree_paypal_checkout/gateway.rb@@ -34,6 +34,7 @@ module SpreePaypalCheckoutendinclude SpreePaypalCheckout::Gateway::PaymentSessions+ include SpreePaypalCheckout::Gateway::Webhookspreference :client_id, :passwordpreference :client_secret, :passworddiff --git a/spree/providers/paypal/app/models/spree_paypal_checkout/gateway/webhooks.rb b/spree/providers/paypal/app/models/spree_paypal_checkout/gateway/webhooks.rbnew file mode 100644index 0000000000..9bd149a284--- /dev/null+++ b/spree/providers/paypal/app/models/spree_paypal_checkout/gateway/webhooks.rb@@ -0,0 +1,112 @@+module SpreePaypalCheckout+ class Gateway < ::Spree::Gateway+ # Webhook signature verification and registration. Webhooks only report+ # money that has moved: the storefront completes the session as soon as the+ # buyer approves, so the approval itself is not subscribed to.+ module Webhooks+ extend ActiveSupport::Concern++ WEBHOOK_EVENT_ACTIONS = {+ 'PAYMENT.CAPTURE.COMPLETED' => :captured,+ 'PAYMENT.CAPTURE.PENDING' => :authorized,+ 'PAYMENT.AUTHORIZATION.CREATED' => :authorized,+ 'PAYMENT.CAPTURE.DENIED' => :failed,+ 'PAYMENT.CAPTURE.DECLINED' => :failed+ }.freeze++ # Registration subscribes to exactly the events with a handler.+ SUPPORTED_EVENTS = WEBHOOK_EVENT_ACTIONS.keys.freeze++ # Where PayPal puts each value the verification call needs.+ SIGNATURE_HEADERS = {+ auth_algo: 'HTTP_PAYPAL_AUTH_ALGO',+ cert_url: 'HTTP_PAYPAL_CERT_URL',+ transmission_id: 'HTTP_PAYPAL_TRANSMISSION_ID',+ transmission_sig: 'HTTP_PAYPAL_TRANSMISSION_SIG',+ transmission_time: 'HTTP_PAYPAL_TRANSMISSION_TIME'+ }.freeze++ included do+ after_commit :register_webhook_async, on: %i[create update]+ end++ # Translates a PayPal event into the shape core's webhook handler takes.+ # Everything after this (idempotency, locking, payment creation, order+ # completion) belongs to core.+ #+ # @param raw_body [String]+ # @param headers [Hash, ActionDispatch::Http::Headers]+ # @return [Hash, nil] nil for events this gateway does not act on+ # @raise [Spree::PaymentMethod::WebhookSignatureError]+ def parse_webhook_event(raw_body, headers)+ event = verify_webhook_signature(raw_body, headers)++ action = WEBHOOK_EVENT_ACTIONS[event['event_type']]+ return nil unless action++ paypal_order_id = event.dig('resource', 'supplementary_data', 'related_ids', 'order_id')+ return nil if paypal_order_id.blank?++ payment_session = Spree::PaymentSessions::PaypalCheckout.find_by(payment_method: self, external_id: paypal_order_id)+ return nil unless payment_session++ { action: action, payment_session: payment_session }+ end++ def register_webhook+ SpreePaypalCheckout::RegisterWebhook.new.call(payment_method: self)+ end++ # @return [SpreePaypalCheckout::NotificationsClient]+ def notifications_client+ SpreePaypalCheckout::NotificationsClient.new(self)+ end++ private++ # Every delivery is checked with PayPal, in every environment. Anything+ # short of PayPal's SUCCESS is a rejected webhook, which PayPal delivers+ # again later.+ def verify_webhook_signature(raw_body, headers)+ if preferred_webhook_id.blank?+ raise Spree::PaymentMethod::WebhookSignatureError, 'PayPal webhook is not registered for this payment method'+ end++ event = parse_event(raw_body)+ signature = SIGNATURE_HEADERS.transform_values { |key| headers[key] }+ raise Spree::PaymentMethod::WebhookSignatureError, 'Missing PayPal signature headers' if signature.values.any?(&:blank?)++ verdict = notifications_client.verify_webhook_signature(+ raw_body: raw_body, headers: signature, webhook_id: preferred_webhook_id+ )+ raise Spree::PaymentMethod::WebhookSignatureError, 'Invalid webhook signature' unless verdict == 'SUCCESS'++ event+ rescue SpreePaypalCheckout::NotificationsClient::Error, *SpreePaypalCheckout::NotificationsClient::NETWORK_ERRORS,+ PaypalServerSdk::APIException, CoreLibrary::AuthValidationException, Faraday::Error, JSON::ParserError => e+ raise Spree::PaymentMethod::WebhookSignatureError, "PayPal could not verify the webhook: #{e.message}"+ end++ def parse_event(raw_body)+ event = JSON.parse(raw_body.to_s)+ raise Spree::PaymentMethod::WebhookSignatureError, 'Malformed webhook payload' unless event.is_a?(Hash)++ event+ rescue JSON::ParserError+ raise Spree::PaymentMethod::WebhookSignatureError, 'Malformed webhook payload'+ end++ # Registered when the method is created and whenever the credentials+ # change, since a webhook belongs to the REST app they name. Not when+ # registration itself stores the webhook id.+ def register_webhook_async+ return unless previously_new_record? ||+ saved_change_to_preferred_client_id? ||+ saved_change_to_preferred_client_secret? ||+ saved_change_to_preferred_test_mode?++ SpreePaypalCheckout::RegisterWebhookJob.perform_later(id)+ end+ end+ end+enddiff --git a/spree/providers/paypal/app/models/spree_paypal_checkout/notifications_client.rb b/spree/providers/paypal/app/models/spree_paypal_checkout/notifications_client.rbnew file mode 100644index 0000000000..516ec5673d--- /dev/null+++ b/spree/providers/paypal/app/models/spree_paypal_checkout/notifications_client.rb@@ -0,0 +1,82 @@+require 'net/http'++module SpreePaypalCheckout+ # The PayPal calls the SDK does not cover: webhook signature verification and+ # webhook registration under /v1/notifications. None of them moves money; a+ # failed verification is redelivered by PayPal and a failed registration is+ # retried by its job, so short timeouts and no retries are enough.+ class NotificationsClient+ OPEN_TIMEOUT = 5+ READ_TIMEOUT = 10+ # Raised by Net::HTTP when PayPal cannot be reached or does not answer.+ NETWORK_ERRORS = [+ Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout, SocketError, EOFError, OpenSSL::SSL::SSLError,+ Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EHOSTUNREACH, Errno::ETIMEDOUT+ ].freeze++ # PayPal answered with an error status.+ class Error < StandardError; end++ # @param gateway [SpreePaypalCheckout::Gateway]+ def initialize(gateway)+ @gateway = gateway+ end++ # The event is sent as PayPal delivered it, byte for byte: re-encoding it+ # can change how numbers and characters are written.+ #+ # @param raw_body [String] the delivery's body, already known to be JSON+ # @return [String] PayPal's verdict, SUCCESS or FAILURE+ def verify_webhook_signature(raw_body:, headers:, webhook_id:)+ fields = headers.merge(webhook_id: webhook_id).to_json+ body = "#{fields.delete_suffix('}')},\"webhook_event\":#{raw_body}}"++ request(Net::HTTP::Post, '/v1/notifications/verify-webhook-signature', body)['verification_status']+ end++ # @return [Array<Hash>] every webhook of the REST app the credentials belong to+ def list_webhooks+ Array(request(Net::HTTP::Get, '/v1/notifications/webhooks')['webhooks'])+ end++ # @return [Hash] the created webhook+ def create_webhook(url:, event_types:)+ body = { url: url, event_types: event_types.map { |name| { name: name } } }.to_json+ request(Net::HTTP::Post, '/v1/notifications/webhooks', body)+ end++ # @return [Hash] the updated webhook+ def replace_webhook_events(webhook_id, event_types)+ body = [{ op: 'replace', path: '/event_types', value: event_types.map { |name| { name: name } } }].to_json+ request(Net::HTTP::Patch, "/v1/notifications/webhooks/#{webhook_id}", body)+ end++ private++ attr_reader :gateway++ def request(verb, path, body = nil)+ uri = URI.join(gateway.client.config.get_base_uri, path)+ http_request = verb.new(uri)+ http_request['Authorization'] = "Bearer #{access_token}"+ http_request['Content-Type'] = 'application/json'+ http_request['Accept'] = 'application/json'+ http_request.body = body if body++ response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https',+ open_timeout: OPEN_TIMEOUT, read_timeout: READ_TIMEOUT) do |http|+ http.request(http_request)+ end++ parsed = response.body.present? ? JSON.parse(response.body) : {}+ return parsed if response.is_a?(Net::HTTPSuccess)++ raise Error, "PayPal answered #{response.code}: #{[parsed['name'], parsed['message']].compact.join(' — ')}"+ end++ # From the SDK's own OAuth client, so token handling lives in one place.+ def access_token+ @access_token ||= gateway.request_access_token.access_token+ end+ end+enddiff --git a/spree/providers/paypal/app/services/spree_paypal_checkout/register_webhook.rb b/spree/providers/paypal/app/services/spree_paypal_checkout/register_webhook.rbnew file mode 100644index 0000000000..10ed425075--- /dev/null+++ b/spree/providers/paypal/app/services/spree_paypal_checkout/register_webhook.rb@@ -0,0 +1,27 @@+module SpreePaypalCheckout+ # Finds or creates the PayPal webhook for a payment method's URL and stores+ # its id on the method. A webhook found for the URL has its events replaced+ # with the gem's: stores upgraded from 5.x created one by hand, subscribed to+ # other events.+ class RegisterWebhook+ # @param payment_method [SpreePaypalCheckout::Gateway]+ # @return [Hash, nil] the webhook, or nil when the method has no URL+ def call(payment_method:)+ url = payment_method.webhook_url+ return if url.blank?++ events = SpreePaypalCheckout::Gateway::Webhooks::SUPPORTED_EVENTS+ client = payment_method.notifications_client+ existing = client.list_webhooks.find { |webhook| webhook['url'] == url }++ webhook = if existing+ client.replace_webhook_events(existing['id'], events)+ else+ client.create_webhook(url: url, event_types: events)+ end++ payment_method.update!(preferred_webhook_id: webhook['id']) if payment_method.preferred_webhook_id != webhook['id']+ webhook+ end+ end+enddiff --git a/spree/providers/paypal/spec/jobs/spree_paypal_checkout/register_webhook_job_spec.rb b/spree/providers/paypal/spec/jobs/spree_paypal_checkout/register_webhook_job_spec.rbnew file mode 100644index 0000000000..ef6a8e51ad--- /dev/null+++ b/spree/providers/paypal/spec/jobs/spree_paypal_checkout/register_webhook_job_spec.rb@@ -0,0 +1,30 @@+require 'spec_helper'++RSpec.describe SpreePaypalCheckout::RegisterWebhookJob do+ let(:gateway) { create(:paypal_checkout_gateway) }++ it 'registers the webhook of the payment method' do+ registered = []+ allow_any_instance_of(SpreePaypalCheckout::Gateway).to receive(:register_webhook) { |payment_method| registered << payment_method.id }++ described_class.perform_now(gateway.id)++ expect(registered).to eq([gateway.id])+ end++ it 'skips a payment method that no longer exists' do+ expect { described_class.perform_now(0) }.not_to raise_error+ end++ it 'skips a payment method of another kind' do+ other = create(:check_payment_method)++ expect { described_class.perform_now(other.id) }.not_to raise_error+ end++ it 'retries when PayPal cannot be reached' do+ allow_any_instance_of(SpreePaypalCheckout::Gateway).to receive(:register_webhook).and_raise(Net::OpenTimeout)++ expect { described_class.perform_now(gateway.id) }.to have_enqueued_job(described_class).with(gateway.id)+ end+enddiff --git a/spree/providers/paypal/spec/models/spree_paypal_checkout/gateway/webhooks_spec.rb b/spree/providers/paypal/spec/models/spree_paypal_checkout/gateway/webhooks_spec.rbnew file mode 100644index 0000000000..cec5ec67bc--- /dev/null+++ b/spree/providers/paypal/spec/models/spree_paypal_checkout/gateway/webhooks_spec.rb@@ -0,0 +1,170 @@+require 'spec_helper'++RSpec.describe SpreePaypalCheckout::Gateway::Webhooks do+ let(:store) { @default_store }+ let(:gateway) { create(:paypal_checkout_gateway, :with_webhook, store: store) }+ let(:cart) { create(:cart_with_line_items, store: store) }+ let!(:payment_session) do+ create(:paypal_checkout_payment_session, owner: cart, payment_method: gateway, external_id: 'ORDER1234567890AB')+ end+ let(:client) { instance_double(SpreePaypalCheckout::NotificationsClient) }+ let(:headers) do+ {+ 'HTTP_PAYPAL_AUTH_ALGO' => 'SHA256withRSA',+ 'HTTP_PAYPAL_CERT_URL' => 'https://api.sandbox.paypal.com/v1/notifications/certs/CERT-1',+ 'HTTP_PAYPAL_TRANSMISSION_ID' => 'transmission-1',+ 'HTTP_PAYPAL_TRANSMISSION_SIG' => 'signature',+ 'HTTP_PAYPAL_TRANSMISSION_TIME' => '2026-10-29T10:00:00Z'+ }+ end++ def event_body(event_type, order_id: 'ORDER1234567890AB')+ {+ id: 'WH-EVENT-1',+ event_type: event_type,+ resource: { id: 'CAPTURE123456789A', supplementary_data: { related_ids: { order_id: order_id } } }+ }.to_json+ end++ before do+ allow(gateway).to receive(:notifications_client).and_return(client)+ allow(client).to receive(:verify_webhook_signature).and_return('SUCCESS')+ end++ it 'subscribes to exactly the events it handles' do+ expect(described_class::SUPPORTED_EVENTS).to contain_exactly(+ 'PAYMENT.CAPTURE.COMPLETED', 'PAYMENT.CAPTURE.PENDING', 'PAYMENT.AUTHORIZATION.CREATED',+ 'PAYMENT.CAPTURE.DENIED', 'PAYMENT.CAPTURE.DECLINED'+ )+ end++ describe '#parse_webhook_event' do+ {+ 'PAYMENT.CAPTURE.COMPLETED' => :captured,+ 'PAYMENT.CAPTURE.PENDING' => :authorized,+ 'PAYMENT.AUTHORIZATION.CREATED' => :authorized,+ 'PAYMENT.CAPTURE.DENIED' => :failed,+ 'PAYMENT.CAPTURE.DECLINED' => :failed+ }.each do |event_type, action|+ it "translates #{event_type} into #{action} for the order's session" do+ expect(gateway.parse_webhook_event(event_body(event_type), headers)).to eq(+ action: action, payment_session: payment_session+ )+ end+ end++ it 'sends the delivery, its signature headers and the webhook id to PayPal' do+ body = event_body('PAYMENT.CAPTURE.COMPLETED')+ gateway.parse_webhook_event(body, headers)++ expect(client).to have_received(:verify_webhook_signature).with(+ raw_body: body,+ webhook_id: 'WH-TEST-1234567890',+ headers: {+ auth_algo: 'SHA256withRSA',+ cert_url: 'https://api.sandbox.paypal.com/v1/notifications/certs/CERT-1',+ transmission_id: 'transmission-1',+ transmission_sig: 'signature',+ transmission_time: '2026-10-29T10:00:00Z'+ }+ )+ end++ %w[CHECKOUT.ORDER.APPROVED PAYMENT.CAPTURE.REFUNDED PAYMENT.CAPTURE.REVERSED].each do |event_type|+ it "ignores #{event_type}" do+ expect(gateway.parse_webhook_event(event_body(event_type), headers)).to be_nil+ end+ end++ it 'ignores an order it has no session for' do+ expect(gateway.parse_webhook_event(event_body('PAYMENT.CAPTURE.COMPLETED', order_id: 'OTHERORDER1234567'), headers)).to be_nil+ end++ it "ignores another payment method's session" do+ other = create(:paypal_checkout_gateway, :with_webhook, store: store)+ allow(other).to receive(:notifications_client).and_return(client)++ expect(other.parse_webhook_event(event_body('PAYMENT.CAPTURE.COMPLETED'), headers)).to be_nil+ end++ it 'only translates the event' do+ expect { gateway.parse_webhook_event(event_body('PAYMENT.CAPTURE.COMPLETED'), headers) }.+ not_to(change { [payment_session.reload.status, Spree::Payment.count] })+ end++ context 'when verification fails' do+ def parse(body = event_body('PAYMENT.CAPTURE.COMPLETED'), with_headers = headers)+ gateway.parse_webhook_event(body, with_headers)+ end++ it 'rejects a signature PayPal does not confirm' do+ allow(client).to receive(:verify_webhook_signature).and_return('FAILURE')++ expect { parse }.to raise_error(Spree::PaymentMethod::WebhookSignatureError, 'Invalid webhook signature')+ end++ it 'rejects every delivery while no webhook id is stored, in every environment' do+ gateway.preferred_webhook_id = nil++ expect { parse }.to raise_error(Spree::PaymentMethod::WebhookSignatureError, /not registered/)+ expect(client).not_to have_received(:verify_webhook_signature)+ end++ it 'rejects a malformed body' do+ expect { parse('{not json') }.to raise_error(Spree::PaymentMethod::WebhookSignatureError, 'Malformed webhook payload')+ end++ it 'rejects a delivery without the signature headers' do+ expect { parse(event_body('PAYMENT.CAPTURE.COMPLETED'), headers.except('HTTP_PAYPAL_TRANSMISSION_SIG')) }.+ to raise_error(Spree::PaymentMethod::WebhookSignatureError, 'Missing PayPal signature headers')+ end++ it 'rejects a delivery when PayPal cannot be reached' do+ allow(client).to receive(:verify_webhook_signature).and_raise(Net::ReadTimeout)++ expect { parse }.to raise_error(Spree::PaymentMethod::WebhookSignatureError, /could not verify/)+ end++ it 'rejects a delivery when PayPal answers with an error' do+ allow(client).to receive(:verify_webhook_signature).+ and_raise(SpreePaypalCheckout::NotificationsClient::Error, 'PayPal answered 500')++ expect { parse }.to raise_error(Spree::PaymentMethod::WebhookSignatureError, /could not verify/)+ end+ end+ end++ describe 'registration' do+ include ActiveJob::TestHelper++ it 'is queued when a method is created' do+ expect { create(:paypal_checkout_gateway, store: store) }.+ to have_enqueued_job(SpreePaypalCheckout::RegisterWebhookJob)+ end++ it 'is queued when the credentials change' do+ gateway++ expect { gateway.update!(preferred_client_secret: 'rotated') }.+ to have_enqueued_job(SpreePaypalCheckout::RegisterWebhookJob).with(gateway.id)+ end++ it 'is queued when test mode changes' do+ gateway++ expect { gateway.update!(preferred_test_mode: false) }.to have_enqueued_job(SpreePaypalCheckout::RegisterWebhookJob)+ end++ it 'is not queued when registration stores the webhook id' do+ gateway++ expect { gateway.update!(preferred_webhook_id: 'WH-NEW') }.not_to have_enqueued_job(SpreePaypalCheckout::RegisterWebhookJob)+ end++ it 'is not queued for an unrelated change' do+ gateway++ expect { gateway.update!(name: 'PayPal (renamed)') }.not_to have_enqueued_job(SpreePaypalCheckout::RegisterWebhookJob)+ end+ end+enddiff --git a/spree/providers/paypal/spec/models/spree_paypal_checkout/notifications_client_spec.rb b/spree/providers/paypal/spec/models/spree_paypal_checkout/notifications_client_spec.rbnew file mode 100644index 0000000000..dc364bd2d4--- /dev/null+++ b/spree/providers/paypal/spec/models/spree_paypal_checkout/notifications_client_spec.rb@@ -0,0 +1,118 @@+require 'spec_helper'++RSpec.describe SpreePaypalCheckout::NotificationsClient do+ subject(:client) { described_class.new(gateway) }++ let(:gateway) { create(:paypal_checkout_gateway, :with_webhook) }+ let(:base) { 'https://api-m.sandbox.paypal.com' }++ before do+ allow(gateway).to receive(:request_access_token).and_return(double(access_token: 'A21AAtoken'))+ end++ describe '#verify_webhook_signature' do+ let(:raw_body) { '{"id":"WH-EVENT-1","event_type":"PAYMENT.CAPTURE.COMPLETED","resource":{"amount":{"value":"10.00"}}}' }+ let(:signature) do+ { auth_algo: 'SHA256withRSA', cert_url: 'https://cert', transmission_id: 't-1', transmission_sig: 'sig', transmission_time: 'now' }+ end++ it 'posts the event as delivered, with the bearer token from the SDK, and returns the verdict' do+ stub = stub_request(:post, "#{base}/v1/notifications/verify-webhook-signature").+ with(headers: { 'Authorization' => 'Bearer A21AAtoken' }) { |request|+ request.body.end_with?(%(,"webhook_event":#{raw_body}})) &&+ JSON.parse(request.body)['webhook_id'] == 'WH-TEST-1234567890'+ }.+ to_return(status: 200, body: { verification_status: 'SUCCESS' }.to_json)++ expect(client.verify_webhook_signature(raw_body: raw_body, headers: signature, webhook_id: 'WH-TEST-1234567890')).+ to eq('SUCCESS')+ expect(stub).to have_been_requested+ end++ it 'raises naming the status when PayPal answers with an error' do+ stub_request(:post, "#{base}/v1/notifications/verify-webhook-signature").+ to_return(status: 400, body: { name: 'VALIDATION_ERROR', message: 'Invalid request' }.to_json)++ expect { client.verify_webhook_signature(raw_body: '{}', headers: signature, webhook_id: 'WH-1') }.+ to raise_error(described_class::Error, 'PayPal answered 400: VALIDATION_ERROR — Invalid request')+ end++ it 'lets a timeout through for the caller to treat as unverified' do+ stub_request(:post, "#{base}/v1/notifications/verify-webhook-signature").to_timeout++ expect { client.verify_webhook_signature(raw_body: '{}', headers: signature, webhook_id: 'WH-1') }.+ to raise_error(Net::OpenTimeout)+ end++ it 'uses short timeouts' do+ expect(described_class::OPEN_TIMEOUT).to be <= 5+ expect(described_class::READ_TIMEOUT).to be <= 10+ end++ context 'against PayPal' do+ # Recording needs the headers and body of a real sandbox delivery (the+ # webhook simulator's events never verify), in PAYPAL_WEBHOOK_HEADERS+ # (JSON of the five values) and PAYPAL_WEBHOOK_BODY, and the receiving+ # webhook's id in PAYPAL_WEBHOOK_ID.+ let(:recorded_headers) { JSON.parse(ENV.fetch('PAYPAL_WEBHOOK_HEADERS', signature.to_json)).symbolize_keys }+ let(:recorded_body) { ENV.fetch('PAYPAL_WEBHOOK_BODY', raw_body) }+ let(:webhook_id) { ENV.fetch('PAYPAL_WEBHOOK_ID', 'WH-TEST-1234567890') }++ before { allow(gateway).to receive(:request_access_token).and_call_original }++ it 'confirms a genuine delivery', vcr: { cassette_name: 'verify_webhook_signature_valid' } do+ expect(client.verify_webhook_signature(raw_body: recorded_body, headers: recorded_headers, webhook_id: webhook_id)).+ to eq('SUCCESS')+ end++ it 'refuses an altered delivery', vcr: { cassette_name: 'verify_webhook_signature_invalid' } do+ altered = recorded_body.sub('"id":"', '"id":"X')++ expect(client.verify_webhook_signature(raw_body: altered, headers: recorded_headers, webhook_id: webhook_id)).+ to eq('FAILURE')+ end+ end+ end++ describe '#list_webhooks' do+ it 'returns the webhooks' do+ stub_request(:get, "#{base}/v1/notifications/webhooks").+ to_return(status: 200, body: { webhooks: [{ id: 'WH-1', url: 'https://shop.example/hook' }] }.to_json)++ expect(client.list_webhooks).to eq([{ 'id' => 'WH-1', 'url' => 'https://shop.example/hook' }])+ end+ end++ describe '#create_webhook' do+ it 'subscribes the URL to the given events' do+ stub = stub_request(:post, "#{base}/v1/notifications/webhooks").+ with(body: { url: 'https://shop.example/hook', event_types: [{ name: 'PAYMENT.CAPTURE.COMPLETED' }] }.to_json).+ to_return(status: 201, body: { id: 'WH-1' }.to_json)++ expect(client.create_webhook(url: 'https://shop.example/hook', event_types: ['PAYMENT.CAPTURE.COMPLETED'])).+ to eq('id' => 'WH-1')+ expect(stub).to have_been_requested+ end+ end++ describe '#replace_webhook_events' do+ it 'replaces the whole event list' do+ stub = stub_request(:patch, "#{base}/v1/notifications/webhooks/WH-1").+ with(body: [{ op: 'replace', path: '/event_types', value: [{ name: 'PAYMENT.CAPTURE.COMPLETED' }] }].to_json).+ to_return(status: 200, body: { id: 'WH-1' }.to_json)++ client.replace_webhook_events('WH-1', ['PAYMENT.CAPTURE.COMPLETED'])++ expect(stub).to have_been_requested+ end+ end++ it 'talks to the live site outside test mode' do+ gateway.preferred_test_mode = false+ stub = stub_request(:get, 'https://api-m.paypal.com/v1/notifications/webhooks').to_return(status: 200, body: '{}')++ client.list_webhooks++ expect(stub).to have_been_requested+ end+enddiff --git a/spree/providers/paypal/spec/services/spree_paypal_checkout/register_webhook_spec.rb b/spree/providers/paypal/spec/services/spree_paypal_checkout/register_webhook_spec.rbnew file mode 100644index 0000000000..ba88736962--- /dev/null+++ b/spree/providers/paypal/spec/services/spree_paypal_checkout/register_webhook_spec.rb@@ -0,0 +1,69 @@+require 'spec_helper'++RSpec.describe SpreePaypalCheckout::RegisterWebhook do+ subject(:register) { described_class.new.call(payment_method: gateway) }++ let(:store) { @default_store }+ let(:gateway) { create(:paypal_checkout_gateway, store: store) }+ let(:client) { instance_double(SpreePaypalCheckout::NotificationsClient) }+ let(:events) { SpreePaypalCheckout::Gateway::Webhooks::SUPPORTED_EVENTS }++ before { allow(gateway).to receive(:notifications_client).and_return(client) }++ context 'when PayPal has no webhook for the URL' do+ before do+ allow(client).to receive(:list_webhooks).and_return([{ 'id' => 'WH-OTHER', 'url' => 'https://other.example/hook' }])+ allow(client).to receive(:create_webhook).and_return({ 'id' => 'WH-NEW' })+ end++ it "creates one subscribed to the gem's events and stores its id" do+ register++ expect(client).to have_received(:create_webhook).with(url: gateway.webhook_url, event_types: events)+ expect(gateway.reload.preferred_webhook_id).to eq('WH-NEW')+ end+ end++ context 'when PayPal has a webhook for the URL' do+ before do+ allow(client).to receive(:list_webhooks).and_return([{ 'id' => 'WH-EXISTING', 'url' => gateway.webhook_url }])+ allow(client).to receive(:replace_webhook_events).and_return({ 'id' => 'WH-EXISTING' })+ allow(client).to receive(:create_webhook)+ end++ it "replaces its events with the gem's and stores its id" do+ register++ expect(client).to have_received(:replace_webhook_events).with('WH-EXISTING', events)+ expect(client).not_to have_received(:create_webhook)+ expect(gateway.reload.preferred_webhook_id).to eq('WH-EXISTING')+ end+ end++ it 'does nothing without a webhook URL' do+ allow(gateway).to receive(:webhook_url).and_return(nil)+ allow(client).to receive(:list_webhooks)++ expect(register).to be_nil+ expect(client).not_to have_received(:list_webhooks)+ end++ context 'against PayPal' do+ # PayPal only takes a public https URL; PAYPAL_WEBHOOK_URL names one.+ before do+ allow(gateway).to receive(:notifications_client).and_call_original+ allow(gateway).to receive(:webhook_url).and_return(ENV.fetch('PAYPAL_WEBHOOK_URL', 'https://spree-paypal.example.com/api/v3/webhooks/payments/pm_test'))+ end++ it 'creates a webhook', vcr: { cassette_name: 'register_webhook_new' } do+ expect(register['id']).to be_present+ expect(gateway.reload.preferred_webhook_id).to eq(register['id'])+ end++ it "replaces an existing webhook's events", vcr: { cassette_name: 'register_webhook_existing' } do+ webhook = register++ expect(webhook['event_types'].map { |event| event['name'] }).to match_array(events)+ end+ end+end