Skip to content

Instantly share code, notes, and snippets.

@BDQ
Created November 9, 2012 17:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BDQ/4046892 to your computer and use it in GitHub Desktop.
Save BDQ/4046892 to your computer and use it in GitHub Desktop.
Spree API patches to allow 'checkout'.
#order model decorator
Order.class_eval do
accepts_nested_attributes_for :line_items, :allow_destroy => true
def self.build_from_api(user, params)
order = create
params[:line_items_attributes].each do |line_item|
order.add_variant(Spree::Variant.find(line_item[:variant_id]), line_item[:quantity])
end
if params.key?(:email)
password_seed = SecureRandom.base64(28)
password = (0...20).map{ password_seed[rand(password_seed.length)] }.join
user = Spree::User.find_or_create_by_email(params[:email],
:login => params[:email],
:password => password,
:password_confirmation => password)
end
order.user = user
order.email = user.email
order.build_ship_address(params['ship_address_attributes']) if params.key? 'ship_address_attributes'
order.build_bill_address(params['bill_address_attributes']) if params.key? 'bill_address_attributes'
if order.line_items.present? && order.ship_address.present? && order.bill_address.present? && order.valid?
order.shipping_method = order.available_shipping_methods(:front_end).first
until order.payment?
order.next!
end
end
order
end
end
#api controller decorator
Spree::Api::V1::PaymentsController.class_eval do
def create
# one of my uglier hacks to fix issue where failed
# payments are reverting to 'checkout' state instead
# of correctly staying 'failed' due to a ROLLBACK
# cause unknown (me think's core issues).
#
@bad_payments = @order.payments.select &:checkout?
if @bad_payments.present?
@bad_payments.each {|p| p.destroy }
@order.reload
end
# build as normal
@payment = @order.payments.build(params[:payment])
if @payment.save
# try to progress order to completed state.
if @order.next
@order.reload #gets most uptodate payment_state
end
render :create, :status => 201
else
invalid_resource!(@payment)
end
end
end
@BDQ
Copy link
Author

BDQ commented Nov 9, 2012

  1. Post to OrderController with everything except the payment.

  2. Then post to Payment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment