Skip to content

Commit

Permalink
checkout for all items in shopping cart
Browse files Browse the repository at this point in the history
  • Loading branch information
yshmarov committed Mar 10, 2021
1 parent a34883d commit 6e30df9
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 7 deletions.
15 changes: 15 additions & 0 deletions README.md
Expand Up @@ -196,3 +196,18 @@ Items:
<%= link_to "x", remove_from_cart_path(cart_item), method: :delete %>
<% end %>
```

## transform items from shopping cart into stripe line_items
product.rb
```
def to_builder
Jbuilder.new do |product|
product.price stripe_price_id
product.quantity 1
end
end
```
checkout_controller
```
@cart.collect { |item| item.to_builder.attributes! },
```
6 changes: 1 addition & 5 deletions app/controllers/checkout_controller.rb
@@ -1,14 +1,10 @@
class CheckoutController < ApplicationController

def create
product = Product.find(params[:id])
@session = Stripe::Checkout::Session.create({
customer: current_user.stripe_customer_id,
payment_method_types: ['card'],
line_items: [{
price: product.stripe_price_id,
quantity: 1
}],
line_items: @cart.collect { |item| item.to_builder.attributes! },
mode: 'payment',
success_url: success_url + "?session_id={CHECKOUT_SESSION_ID}",
cancel_url: cancel_url,
Expand Down
7 changes: 7 additions & 0 deletions app/models/product.rb
Expand Up @@ -6,6 +6,13 @@ def to_s
name
end

def to_builder
Jbuilder.new do |product|
product.price stripe_price_id
product.quantity 1
end
end

after_create do
product = Stripe::Product.create(name: name)
price = Stripe::Price.create(product: product, unit_amount: self.price, currency: "usd")
Expand Down
4 changes: 4 additions & 0 deletions app/views/layouts/application.html.erb
Expand Up @@ -29,6 +29,10 @@
<%= product.name %>
<br>
<% end %>
<% if @cart.present? %>
<%= @cart.collect { |item| item.to_builder.attributes! } %>
<%= button_to "Buy now!", checkout_create_path, remote: true, data: { disable_with: "validating..."} %>
<% end %>
<hr>
<%= yield %>
</body>
Expand Down
2 changes: 0 additions & 2 deletions app/views/products/index.html.erb
Expand Up @@ -10,7 +10,6 @@
<th>Stripe Product Id</th>
<th>Stripe Price Id</th>
<th>Shopping cart</th>
<th>PAYMENT</th>
<th>Sales count</th>
<th colspan="3"></th>
</tr>
Expand All @@ -30,7 +29,6 @@
<%= button_to "Add to cart", add_to_cart_path(product) %>
<% end %>
</td>
<td><%= button_to "Buy now!", checkout_create_path, params: {id: product.id}, remote: true, data: { disable_with: "validating..."} %></td>
<td><%= product.sales_count %></td>
<td><%= link_to 'Show', product %></td>
<td><%= link_to 'Edit', edit_product_path(product) %></td>
Expand Down

0 comments on commit 6e30df9

Please sign in to comment.