【发布时间】:2023-03-25 14:09:01
【问题描述】:
我正在尝试在 Ruby 中完成我的付款设置,但我正在努力打印订单确认屏幕。我已经设置了我的部分付款方式。
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
data-image="<%= asset_path(@product.image_url) %>"
data-name="<%= @product.name %>"
data-description="<%= @product.description %>"
data-amount="<%= @product.price*100.to_i %>">
</script>
我的付款控制器。
class PaymentsController < ApplicationController
before_action :authenticate_user!
def create
@product = Product.find(params[:product_id])
@user = current_user
token = params[:stripeToken]
# Create the charge on Stripe's servers - this will charge the user's card
begin
charge = Stripe::Charge.create(
amount: @product.price, # amount in cents, again
currency: "eur",
source: token,
description: params[:stripeEmail]
)
if charge.paid
UserMailer.order_confirmation(@user, @product).deliver_now
Order.create!(
:product_id => @product.id,
:user_id => @user.id,
:total => @product.price_show
)
flash[:success] = "Your payment was processed successfully"
end
rescue Stripe::CardError => e
body = e.json_body
err = body[:error]
flash[:error] = "Unfortunately, there was an error processing your payment: #{err[:message]} Your card has not been charged. Please try again."
end
redirect_to product_path(@product), notice: "Thank you for your purchase."
end
end
还有我的路线文件。
Rails.application.routes.draw do
devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout' },
controllers: {registrations: "user_registrations"}
resources :products do
resources :comments
end
post 'payments/create'
resources :users
resources :orders, only: [:index, :show, :create, :destroy]
resources :users, except: [:index]
get 'simple_pages/about'
get 'simple_pages/contact'
root 'simple_pages#landing_page'
post 'simple_pages/thank_you'
mount ActionCable.server => '/cable'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
产品show.html.erb中的表单
<%= form_with(url: '/payments/create') do |form| %>
<%= render partial: "shared/stripe_checkout_button" %>
<%= hidden_field_tag(:product_id, @product.id) %>
<% end %>
但是,当我尝试完成测试付款时,我的操作控制器弹出“找不到没有 ID 的产品”。我认为这是在创建部分中定义的,但我不知道如何纠正这个问题。任何建议将不胜感激。
【问题讨论】:
-
控制器接收到哪些参数? rails 抛出的错误是因为它在执行时找不到没有 id 的 ActiveRecord 对象 -
Product.find(params[:product_id]) -
您能分享一下new.html 或表格吗?正如@AlokSwain 提到的,似乎 product_id 没有设置
-
刚刚添加。
-
@Jac89,表格看起来正确。但是
product数据不是您可以检查以下 1) 在您的表单中,检查并查看product_id的隐藏值是什么,以确保它具有价值? 2) 在你的控制器的def create中,打印出params[:product_id]确保它是一个有效的产品ID 它更像是一个数据问题,检查以上以确保 -
@wsw 完美!解决了那里的一切。再次感谢!
标签: ruby ruby-on-rails-5 stripe-payments