Skip to content

Instantly share code, notes, and snippets.

@briansw
Created August 28, 2015 22:32
Show Gist options
  • Save briansw/e2ce579bf3bed5a07c9a to your computer and use it in GitHub Desktop.
Save briansw/e2ce579bf3bed5a07c9a to your computer and use it in GitHub Desktop.
def submit
@order = Order.find(params[:id])
begin
customer = Stripe::Customer.create(
email: params[:order][:email],
:card => params[:order][:stripe_token]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => params[:order_total_price],
description: params[:order][:email],
:currency => 'usd'
)
rescue Stripe::CardError => e
render json: { status: 'failure', message: e.message, template: nil }
else
finalize_order
end
end
def finalize_order
update_quantities
if @order.update_attributes(params[:order])
@order.billing_name = charge.card.name
@order.stripe_token = charge.id
@order.state_tax = params[:order_sales_tax]
transaction = { order_id: charge.id,
total: (@order.subtotal/100),
tax: (@order.state_tax/100),
shipping: (@order.shipping/100),
city: @order.city,
state: @order.state,
country: @order.country
}
items = []
@order.line_items.each do |line_item|
item = { order_id: charge.id,
sku_id: line_item.sku.id,
sku_name: line_item.sku.long_title,
product_type: line_item.sku.product.product_type.title,
price: (line_item.sku.product_real_price/100), quantity: line_item.quantity
}
items << item
end
@order.save
template = render_to_string(template: '/carts/_receipt', layout: false, locals: { order: @order })
render json: { status: 'success', template: template, items: items, transaction: transaction }
OrderNotifier.received(@order).deliver
else
template = render_to_string(template: '/carts/_receipt', layout: false, locals: { order: @order })
render json: { status: 'failure', alert: 'Something went wrong' }
end
end
def update_quantities
@cart.destroy
session[:cart_id] = nil
@order.line_items.each do |line_item|
@sku = line_item.sku
@sku.quantity = @sku.quantity - line_item.quantity
if @sku.quantity < 0
@sku.quantity = 0
end
@sku.save
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment