lib/sinatra/paypal.rb in sinatra-paypal-0.2.0 vs lib/sinatra/paypal.rb in sinatra-paypal-0.3.0

- old
+ new

@@ -2,19 +2,13 @@ require 'sinatra/base' require 'sinatra/paypal/version' require 'sinatra/paypal/paypal-helper' require 'sinatra/paypal/paypal-request' -PAYPAL_BLOCKS = {} - module PayPal module Helpers - def _paypal_block(name) - return Proc.new{} if !PAYPAL_BLOCKS.key? name - PAYPAL_BLOCKS[name] - end def paypal_form_url PaypalHelper.form_url(settings.paypal.sandbox?) end @@ -37,10 +31,11 @@ end end def self.registered(app) app.helpers PayPal::Helpers + app._paypal_register_default_callbacks app.set :paypal, OpenStruct.new({ :return_url => '/payment/complete', :notify_url => '/payment/validate', :sandbox? => app.settings.development?, @@ -51,31 +46,29 @@ paypal_helper = PaypalHelper.new(app.settings.paypal.sandbox?) paypal_request = PaypalRequest.new(params) # first we check the request against paypal to make sure it is ok if settings.production? - halt 400, 'request could not be validated' if !paypal_helper.ipn_valid? params + halt 500, 'request could not be validated' if !paypal_helper.ipn_valid? params end - - halt 400, 'no username provided' if paypal_request.username.nil? # check transaction log to make sure this not a replay attack - if instance_exec(paypal_request, &_paypal_block(:repeated?)) + if app._call_paypal_method(:repeated?, paypal_request) # we also want to return 200, because if it is paypal sending this, it will send # it again and again until it gets a 200 back halt 200, 'already processed' end - instance_exec(paypal_request, &_paypal_block(:validate!)) + app._call_paypal_method(:validate!, paypal_request) # check that the payment is complete. we still return 200 if not, but # we don't need to do anymore processing (except for marking it as accountable, if it is) if paypal_request.complete? - instance_exec(paypal_request, &_paypal_block(:complete)) + app._call_paypal_method(:complete, paypal_request) end - instance_exec(paypal_request, &_paypal_block(:finish)) + app._call_paypal_method(:finish, paypal_request) return 200 end end @@ -87,11 +80,35 @@ # # process the payment here # # don't forget to check that the price is correct! # end # def payment(name, &block) - PAYPAL_BLOCKS[name] = block + raise "#{name.to_s} is not a valid payment callback" if !_paypal_valid_blocks.include? name + _paypal_register_callback name, &block end + + def _paypal_register_default_callbacks + _paypal_valid_blocks.each do |key| + _paypal_register_callback(key) { |p| } + end + end + + def _paypal_register_callback(key, &block) + self.class.send :define_method, _paypal_method_name(key), &block + end + + def _paypal_valid_blocks + [:complete, :finish, :validate!, :repeated?] + end + + def _call_paypal_method(key, paypal_request) + self.send _paypal_method_name(key), paypal_request + end + + def _paypal_method_name(key) + "payment_event_#{key}".to_sym + end + end module Sinatra register PayPal