Skip to content
This repository has been archived by the owner on Apr 14, 2023. It is now read-only.

Fix ambiguous behavior in generate_token method #209

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ class ClientTokensController < ::Spree::Api::BaseController
before_action :load_gateway

def create
render json: { client_token: @gateway.generate_token, payment_method_id: @gateway.id }
token = @gateway.generate_token
if token
render json: { client_token: token, payment_method_id: @gateway.id }
else
render json: { error: Gateway::TOKEN_GENERATION_DISABLED_MESSAGE }, status: :unprocessable_entity
end
end

private
Expand All @@ -25,5 +30,12 @@ def load_gateway
@gateway = ::SolidusPaypalBraintree::Gateway.where(active: true).merge(store_payment_methods_scope).first!
end
end

def generate_token
@gateway.generate_token
rescue ::SolidusPaypalBraintree::Gateway::TokenGenerationDisabledError => e
Rails.logger.error e
nil
end
end
end
12 changes: 8 additions & 4 deletions app/models/solidus_paypal_braintree/gateway.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ module SolidusPaypalBraintree
class Gateway < ::Spree::PaymentMethod
include RequestProtection

class TokenGenerationDisabledError < StandardError; end

# Error message from Braintree that gets returned by a non voidable transaction
NON_VOIDABLE_STATUS_ERROR_REGEXP = /can only be voided if status is authorized/.freeze

Expand Down Expand Up @@ -222,12 +224,12 @@ def create_profile(payment)
end
end

# @raise [TokenGenerationDisabledError]
# If `preferred_token_generation_enabled` is false
#
# @return [String]
# The token that should be used along with the Braintree js-client sdk.
#
# returns an error message if `preferred_token_generation_enabled` is
# set to false.
#
# @example
# <script>
# var token = #{Spree::Braintree::Gateway.first!.generate_token}
Expand All @@ -242,7 +244,9 @@ def create_profile(payment)
# );
# </script>
def generate_token
return TOKEN_GENERATION_DISABLED_MESSAGE unless preferred_token_generation_enabled
unless preferred_token_generation_enabled
raise TokenGenerationDisabledError, TOKEN_GENERATION_DISABLED_MESSAGE
end

braintree.client_token.generate
end
Expand Down
2 changes: 1 addition & 1 deletion spec/models/solidus_paypal_braintree/gateway_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -686,7 +686,7 @@
gateway
end

it { is_expected.to match(/Token generation is disabled/) }
it { expect { subject }.to raise_error SolidusPaypalBraintree::Gateway::TokenGenerationDisabledError }
end
end
end