不确定在哪里放置 Stripe API 调用

unsure where to put Stripe API call

这个问题已经思考了几个小时了,我认为这是因为我误解了一些基本的rails知识

this intro Stripe guide中,他们演示了以下代码

def new
end

def create
  # Amount in cents
  @amount = 500

  customer = Stripe::Customer.create(
    :email => 'example@stripe.com',
    :card  => params[:stripeToken]
  )

  charge = Stripe::Charge.create(
    :customer    => customer.id,
    :amount      => @amount,
    :description => 'Rails Stripe customer',
    :currency    => 'usd'
  )

rescue Stripe::CardError => e
  flash[:error] = e.message
  redirect_to charges_path
end

我的问题是,create 操作中的所有代码都必须位于 create 中吗?

我正在尝试按照指南进行操作,但我没有只有一种产品,而是有多种产品。所以我很自然地将代码放在 show 操作中。

class BooksController < ApplicationController

    def index
        @books = Book.all
    end

    def show
        @book = Book.find(params[:id])


        customer = Stripe::Customer.create(
            :email => 'example@stripe.com',
            :card  => params[:stripeToken]
        )

        charge = Stripe::Charge.create(
            :customer    => customer.id,
            :amount      => @book.price,
            :description => 'Rails Stripe customer',
            :currency    => 'usd'
        )

        rescue Stripe::CardError => e
            flash[:error] = e.message
            redirect_to books_path

    end
end

现在,每当我尝试访问任何显示页面 (localhost:3000/books/1) 时,它都会重定向到 books_path,它告诉我存在某种 CardError。

这是怎么回事?

因为你的 show 方法中有这个:

   rescue Stripe::CardError => e
        flash[:error] = e.message
        redirect_to books_path

当您尝试通过 show 操作访问任何页面时,它会尝试创建 charge 并出现错误,因此上面的代码将其挽救并将您重定向到 books_path.所以,这是很正常的行为。

如果您修复收到的 CardError,它将成功创建费用。但是,这不是产生电荷的正确位置。 如本教程本身所示,您应该有一个自定义 controller/view 来创建费用。

在您的展示页面中,您可以有一个产品表单和一个用于购买产品的按钮,当按下按钮时,您的表单应该提交给您创建费用的自定义控制器的操作方法。

是的,您混淆/混合了一些 rails 知识。您需要做的是:

#Create your BooksController
class BooksController < ApplicationController
  def index
    @book = Book.all
  end

  def new
    @book = Book.new
  end 

  def create
    @book = Book.new(book_params)
      if @book.save
        #do something
      else
        #do something
      end
  end

  def show
    @book = Book.find(params[:id])
  end

   #edit
   #destroy    
end

然后,您将单独创建条带交易;这可能在一个名为 Sales.

的控制器中
#Create your SalesController
class SalesController < ApplicationController


  def create
    @book = Book.find(params[:book_id])
      #stripe create code using book attributes (@book.price)



   #after sale in stripe. create record in a sales table.

   Sale.create(book_id: @book.id, amount: @book.price, other stuff)

  end

end

您需要将 sales 操作嵌套在您的路线文件中的书籍操作中。

resources: books do 
  resources :sales
end

这应该会让您朝着正确的方向开始。