Module: Shoppe::Paypal

Defined in:
lib/shoppe/paypal.rb,
lib/shoppe/paypal/engine.rb,
lib/shoppe/paypal/version.rb,
lib/shoppe/paypal/order_extensions.rb,
lib/shoppe/paypal/payment_extensions.rb

Defined Under Namespace

Modules: OrderExtensions, PaymentExtensions Classes: Engine

Constant Summary collapse

VERSION =
"1.2.0"

Class Method Summary collapse

Class Method Details

.client_idObject



14
15
16
# File 'lib/shoppe/paypal.rb', line 14

def client_id
  Shoppe.settings.paypal_client_id
end

.client_secretObject



18
19
20
# File 'lib/shoppe/paypal.rb', line 18

def client_secret
  Shoppe.settings.paypal_client_secret
end

.currencyObject



22
23
24
# File 'lib/shoppe/paypal.rb', line 22

def currency
  Shoppe.settings.paypal_currency
end

.setupObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/shoppe/paypal.rb', line 26

def setup
  # Set the configuration
  Shoppe.add_settings_group :paypal, [:paypal_client_id, :paypal_client_secret, :paypal_currency]

  # When an order is accepted, attempt to capture/execute the payment
  Shoppe::Order.before_acceptance do
    Shoppe::Paypal.setup_paypal

    self.payments.where(confirmed: false, method: "PayPal").each do |payment|
      begin
        payment.paypal_payment.execute(payer_id: payment.order.properties["paypal_payer_id"])

        transaction = payment.paypal_payment.transactions.first.related_resources.first.sale.id

        payment.update_attribute(:confirmed, true)
        payment.update_attribute(:reference, transaction)
      rescue
        raise Shoppe::Errors::PaymentDeclined, "Payment ##{payment.id} could not be captured by PayPal. Investigate with PayPal. Do not accept the order."
      end
    end
  end

  # Refund the PayPal transaction
  Shoppe::Payment.before_refund do
    if self.method == "PayPal"
      Shoppe::Paypal.setup_paypal

      begin
        @sale = PayPal::SDK::REST::Sale.find(self.reference)
        @refund  = @sale.refund({
          :amount => {
            :currency => Shoppe::Paypal.currency,
            :total => "#{'%.2f' % self.refundable_amount}"}
        })
          
        # Check refund status
        if @refund.success?
          true
        else
          raise Shoppe::Errors::RefundFailed, message: "Unable to Refund" 
          logger.error "Unable to Refund"
          logger.error @refund.error.inspect
        end
      rescue
        raise Shoppe::Errors::RefundFailed, message: "PayPal Sale '#{self.reference}' Not Found" 

      end
    end
  end

end

.setup_paypalObject

Setup the PayPal configuration



79
80
81
82
83
84
85
86
87
# File 'lib/shoppe/paypal.rb', line 79

def setup_paypal
  include PayPal::SDK::REST

  PayPal::SDK.configure({
    mode:          (Rails.env.production? ? "live" : "sandbox"),
    client_id:     client_id,
    client_secret: client_secret
  })
end