boomerdigital / solidus_amazon_payments

Add Pay with Amazon to your Spree Commerce solution
Apache License 2.0
7 stars 8 forks source link

Refund fails #64

Open prdanelli opened 6 years ago

prdanelli commented 6 years ago

I believe there is an error in the cancel/void methods within Spree::Gateway::Amazon. When an order is canceled from with the Solidus admin a nil class is passed to the cancel method. This means the Spree::Payment.find_by!(response_code: response_code) finds the first payment with a nil response_code and returns it; this could be the first payment in the table as the default order is id: :asc.

Another issue I found was that the @mws.refund method is incorrect; even though you are assigning the capture_id to a variable, the first argument of the refund call is response_code, not capture_id. This causes an error to be returned from Amazon.

# Current `cancel` method
def cancel(response_code)
  payment = Spree::Payment.find_by!(response_code: response_code)
  # ... Removed for brevity
  capture_id = order.amazon_transaction.capture_id

  if capture_id.nil?
    response = @mws.cancel
  else
    response = @mws.refund(response_code, order.number, payment.credit_allowed, payment.currency)
  end

  # ... Removed for brevity
end

As Solidus is now using try_void instead of cancel, I have provided the working try_void instead of fixing the cancel method.

def try_void(payment)
  order = payment.order
  load_amazon_mws(payment.source.order_reference)
  capture_id = order.amazon_transaction.capture_id

  if capture_id.nil?
    response = @mws.cancel
  else
    response = @mws.refund(capture_id, order.number, payment.credit_allowed, payment.currency)
  end

  return ActiveMerchant::Billing::Response.new(true, "#{order.number}-cancel", Hash.from_xml(response.body))
end