ruby - 获取 Stripe 费用信息 rails 5 创建订单
问题描述
所以我正在实施 Stripe,用户可以成功购买,但是,我想获取费用信息、最后 4 个卡号、卡类型等,以便我可以使用https://github.com/excid3/receipts生成收据.
这是我到目前为止所拥有的:
付款控制器
class PaymentsController < ApplicationController
before_action :authenticate_user!
def create
token = params[:stripeToken]
@course = Course.find(params[:course_id])
@user = current_user
begin
charge = Stripe::Charge.create(
amount: (@course.price*100).to_i,
currency: "gbp",
source: token,
description: params[:stripeEmail],
receipt_email: params[:stripeEmail]
)
if charge.paid
Order.create(
course_id: @course.id,
user_id: @user.id,
Amount: @course.price
)
end
flash[:success] = "Your payment was processed successfully"
rescue Stripe::CardError => e
body = e.json_body
err = body[:error]
flash[:error] = "Unfortunately, there was an error processing your payment: #{err[:message]}"
end
redirect_to course_path(@course)
end
end
订单控制器
class OrdersController < ApplicationController
layout proc { user_signed_in? ? "dashboard" : "application" }
before_action :authenticate_user!
def index
@orders = Order.includes(:course).all
end
def show
@order = Order.find(params[:id])
respond_to do |format|
format.pdf {
send_data @order.receipt.render,
filename: "#{@order.created_at.strftime("%Y-%m-%d")}-aurameir-courses-receipt.pdf",
type: "application/pdf",
disposition: :inline
}
end
end
def create
end
def destroy
end
end
订单.rb
class Order < ApplicationRecord
belongs_to :course
belongs_to :user
validates :stripe_id, uniqueness: true
def receipt
Receipts::Receipt.new(
id: id,
subheading: "RECEIPT FOR CHARGE #%{id}",
product: "####",
company: {
name: "####",
address: "####",
email: "####",
logo: "####"
},
line_items: [
["Date", created_at.to_s],
["Account Billed", "#{user.full_name} (#{user.email})"],
["Product", "####"],
["Amount", "£#{amount / 100}.00"],
["Charged to", "#{card_type} (**** **** **** #{card_last4})"],
["Transaction ID", uuid]
],
font: {
normal: Rails.root.join('app/assets/fonts-converted/font-files/AvenirBook.ttf')
}
)
end
end
架构.rb
create_table "orders", force: :cascade do |t|
t.integer "user_id"
t.integer "course_id"
t.integer "stripe_id"
t.integer "amount"
t.string "card_last4"
t.string "card_type"
t.integer "card_exp_month"
t.integer "card_exp_year"
t.string "uuid"
t.index ["course_id"], name: "index_orders_on_course_id"
t.index ["user_id"], name: "index_orders_on_user_id"
end
我将如何获取收费信息?
解决方案
您需要的所有信息都在charge
您创建的对象中。
if charge.paid
Order.create(
course_id: @course.id,
user_id: @user.id,
amount: @course.price,
card_last4: charge.source.last4,
card_type: charge.source.brand,
card_exp_month: charge.source.exp_month,
card_exp_year: charge.source.exp_year
)
end
有关收费的所有可用信息,请参阅https://stripe.com/docs/api/ruby#charge_object。