Sha256: 12585be5646cbdab76faad570d2cd79426ea96151e8a4d418314577b43b21afa

Contents?: true

Size: 1.82 KB

Versions: 5

Compression:

Stored size: 1.82 KB

Contents

module Moneytree
  module Webhooks
    class StripeController < ApplicationController
      skip_before_action :verify_authenticity_token

      def create
        case webhook_params.type
        when 'charge.succeeded'
          process_charge!
        when 'charge.refunded'
          process_refund!
        else
          puts "Unhandled event type: #{webhook_params.type}"
        end

        head :ok
      end

      private

      def webhook_params
        @webhook_params ||=
          ::Stripe::Event.construct_from(
            JSON.parse(request.body.read, symbolize_names: true)
          )
      end

      def process_charge!
        return if transaction.completed?

        transaction.process_response(
          TransactionResponse.new(:success, '', { charge_id: stripe_object.id })
        )

        if Moneytree.order_status_trigger_method
          transaction.order.send(Moneytree.order_status_trigger_method, transaction)
        end
      end

      def process_refund!
        stripe_object.refunds.data.each do |stripe_refund_object|
          # TODO: Create refund transaction in db for PSP-initiated refunds
          next if stripe_refund_object.metadata[:moneytree_transaction_id].blank?

          refund = transaction.refunds.find(stripe_refund_object.metadata[:moneytree_transaction_id])

          next if refund.completed?

          refund.process_response(
            TransactionResponse.new(:success, '')
          )
          if Moneytree.order_status_trigger_method
            transaction.order.send(Moneytree.order_status_trigger_method, transaction)
          end
        end
      end

      def transaction
        @transaction ||= Transaction.find(stripe_object.metadata[:moneytree_transaction_id])
      end

      def stripe_object
        @stripe_object ||= webhook_params.data.object
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
moneytree-rails-0.1.8 app/controllers/moneytree/webhooks/stripe_controller.rb
moneytree-rails-0.1.7 app/controllers/moneytree/webhooks/stripe_controller.rb
moneytree-rails-0.1.6 app/controllers/moneytree/webhooks/stripe_controller.rb
moneytree-rails-0.1.5 app/controllers/moneytree/webhooks/stripe_controller.rb
moneytree-rails-0.1.4 app/controllers/moneytree/webhooks/stripe_controller.rb