Sha256: f4005c243369dd158318e2a87bc7163fea9fac0ad7f9d90ba5857f32a340b254

Contents?: true

Size: 1.47 KB

Versions: 1

Compression:

Stored size: 1.47 KB

Contents

module Paidy
  class Charge
    class << self
      def create(params)
        res = Paidy.request(:post, 'payments', params, {})

        self.new(res['id'])
      end

      def retrieve(id)
        instance = self.new(id)
        instance.refresh

        instance
      end
    end

    def initialize(id)
      @id = id
      @capture_id = nil
      @amount = nil
      @status = nil
    end

    attr_reader :id, :capture_id, :amount, :status

    def capture
      res = Paidy.request(:post, "#{base_path}/captures", {}, {})
      @capture_id = res['captures'][0]['id']

      self
    end

    def close
      res = Paidy.request(:post, "#{base_path}/close", {}, {})

      self
    end

    def refund(amount: nil, refund_reason: nil)
      params = { capture_id: capture_id }
      params[:amount] = amount if amount.present?
      params[:reason] = refund_reason if refund_reason.present?

      res = Paidy.request(:post, "#{base_path}/refunds", params, {})

      self
    end

    def refund_or_close(amount: nil, refund_reason: nil)
      if capture_id.nil?
        close
      else
        refund(amount: amount, refund_reason: refund_reason)
      end
    end

    def refresh
      res = Paidy.request(:get, "payments/#{id}")

      @amount = res['amount']
      @status = res['status']

      if res['status'] == 'closed' && res['captures'].present?
        @capture_id = res['captures'][0]['id']
      end
    end

    private

    def base_path
      "payments/#{id}"
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
paidy-0.0.6 lib/paidy/charge.rb