【问题标题】:How to check out successfully with Braintree::Transaction.sale without hard coded values?如何在没有硬编码值的情况下使用 Braintree::Transaction.sale 成功签出?
【发布时间】:2018-05-11 01:08:24
【问题描述】:

我能够使用硬编码金额成功结帐,即:

def checkout
    nonce = params["payment_method_nonce"]

    if current_user.braintree_id?
        customer = Braintree::Customer.find(current_user.braintree_id)
    else
        @result = Braintree::Customer.create(
            email: current_user.email,
            payment_method_nonce: params[:payment_method_nonce]
          )
          customer = result.customer
          current_user.update(braintree_id: customer.id)
end

     @result = Braintree::Transaction.sale(
      amount: **"10.00"**,
      payment_method_nonce: nonce
    )

    if @result.success? 
        redirect_to root_path, notice: "You have successfully checked out"
    else
        flash[:alert] = "Something went wrong while processing your transaction"
        render :new
    end
end

假设我希望 current_user 能够以存储在我的 rails 数据库中的特定“价格”购买我的投资组合的访问权限。有没有办法通过从数据库中的对象属性中提取金额来设置金额,即:“”?我已经尝试了多次,但没有任何运气。我可能做错了什么?

【问题讨论】:

    标签: ruby-on-rails ruby payment braintree braintree-sandbox


    【解决方案1】:

    如 Rails 框架的文档中所述:

    ActiveRecord Basics

    您需要从 PortfolioItems 模型表中映射一个新字段。为此,您首先需要通过创建迁移将该字段添加到表中,我建议使用小数,因为如果您在逗号后限制数量,浮点数可能会导致问题。

    每个portfolio_item 都应该以小数形式存储它的价格,小数位数为2:

    t.decimal :price, scale: 2, precision: 5
    

    这将允许该项目具有与之关联的价格,并使方法:@portfolio_item.price 可用。

    然后你只需要在你的控制器中替换:

     @result = Braintree::Transaction.sale(
          amount: **"10.00"**,
          payment_method_nonce: nonce
        )
    

    与:

     @result = Braintree::Transaction.sale(
          amount: @portfolio_item.price,
          payment_method_nonce: nonce
        )
    

    【讨论】:

    • "每个portfolio_item 的价格都应该以十进制形式存储,小数位数为2,这将允许该项目有一个与之关联的价格,并使方法:@portfolio_item.price 可用。" - 为什么会这样,它在哪里记录,以及怎么会有人知道这一点?是否只是一个让特定列类型可用作价格方法的 rails 东西?
    • 已更新答案,抱歉缺少来源。
    猜你喜欢
    • 1970-01-01
    • 2018-06-09
    • 2020-03-06
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多