9

저는 Stripe and Rails on Rails 3.2의 작은 개념 증명을 만들고 있습니다. 지금까지 RoR 앱에서 Stripe을 구현하는 방법에 대해 Railscast를 보았습니다. 실제로 잘 작동합니다.스트라이프 예외를 처리하는 위치와 방법은 무엇입니까?

나는 RailsCast #288 Billing with Stripe을 따라 내 앱을 만들었습니다. 이제 사용자는 신용 카드를 추가 및 편집하고 수업에 등록하고 완료되면 신용 카드로 청구 할 수 있습니다.

이제는 스트라이프의 수많은 test credit cards으로 테스트 해 보았습니다. 발생했을 때 많은 예외를 잡으려고합니다.

class Registration < ActiveRecord::Base 

    belongs_to :user 
    belongs_to :session 

    attr_accessible :session_id, :user_id, :session, :user, :stripe_payment_id 
    validates :user_id, :uniqueness => {:scope => :session_id} 

    def save_with_payment(user, stripe_card_token) 
    if valid? 
     if user.stripe_customer_id.present? 
     charge = Stripe::Charge.create(
      :customer => user.stripe_customer_id, 
      :amount => self.session.price.to_i * 100, 
      :description => "Registration for #{self.session.name} (Id:#{self.session.id})", 
      :currency => 'cad' 
     ) 
     else 
     customer = Stripe::Customer.create(
      :email => user.email, 
      :card => stripe_card_token, 
      :description => user.name 
     ) 
     charge = Stripe::Charge.create(
      :customer => customer.id, 
      :amount => self.session.price.to_i * 100, 
      :description => "Registration for #{self.session.name} (Id:#{self.session.id})", 
      :currency => 'cad' 
     ) 
     user.update_attribute(:stripe_customer_id, customer.id) 
     end 
     self.stripe_payment_id = charge.id 
     save! 
    end 
    rescue Stripe::CardError => e 
    body = e.json_body 
    err = body[:error] 
    logger.debug "Status is: #{e.http_status}" 
    logger.debug "Type is: #{err[:type]}" 
    logger.debug "Code is: #{err[:code]}" 
    logger.debug "Param is: #{err[:param]}" 
    logger.debug "Message is: #{err[:message]}" 
    rescue Stripe::InvalidRequestError => e 
    # Invalid parameters were supplied to Stripe's API 
    rescue Stripe::AuthenticationError => e 
    # Authentication with Stripe's API failed 
    # (maybe you changed API keys recently) 
    rescue Stripe::APIConnectionError => e 
    # Network communication with Stripe failed 
    rescue Stripe::StripeError => e 
    # Display a very generic error to the user, and maybe send 
    # yourself an email 
    rescue => e 
    # Something else happened, completely unrelated to Stripe 
    end 
end 

나는 단지 지금 오류를 구출 정말 한 후 조치를 취하지 않는거야가 제기되고 궁극적으로 나는 현재 클래스를 중단하고 싶습니다 : 여기 쇼로 내 등록 모델에서 스트라이프의 example 오류를 사용하고 있습니다 등록이 일어나지 않도록하고 플래시 오류가있는 사용자를 리디렉션합니다.

나는 rescure_from에 대해 읽었지만 모든 가능한 스트라이프 오류를 처리하는 가장 좋은 방법은 무엇인지 잘 모르겠습니다. 모델에서 리디렉션 할 수 없다는 것을 알고 있습니다. 어떻게 전문가가이 문제를 처리합니까?

가 여기 내 등록 컨트롤러의 : 응답 시간을내어

class Classroom::RegistrationsController < ApplicationController 
    before_filter :authenticate_user! 

    def new 
    if params[:session_id] 
     @session = Session.find(params[:session_id]) 
     @registration = Registration.new(user: current_user, session: @session) 
    else 
     flash[:error] = "Course session is required" 
    end 

    rescue ActiveRecord::RecordNotFound 
     render file: 'public/404', status: :not_found 

    end 

    def create 
    if params[:session_id] 
     @session = Session.find(params[:session_id]) 
     @registration = Registration.new(user: current_user, session: @session) 
     if @registration.save_with_payment(current_user, params[:stripe_card_token]) 
     flash[:notice] = "Course registration saved with success." 
     logger.debug "Course registration saved with success." 
     mixpanel.track 'Registered to a session', { :distinct_id => current_user.id, 
              :id => @session.id, 
              'Name' => @session.name, 
              'Description' => @session.description, 
              'Course' => @session.course.name 
     } 
     mixpanel.increment current_user.id, { :'Sessions Registered' => 1} 
     mixpanel.track_charge(current_user.id, @session.price.to_i) 
     else 
     flash[:error] = "There was a problem saving the registration." 
     logger.debug "There was a problem saving the registration." 
     end 
     redirect_to root_path 
    else 
     flash[:error] = "Session required." 
     redirect_to root_path 
    end 
    end 

end 

감사합니다, 많은 감사!

프랜시스

답변

10

당신은 사용자 정의 유효성 검사기에 실제로 스트라이프 전화를 넣어 생각 했습니까?

http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validate

그냥 두지 왜 뒤에 논리 만 어쨌든 '거래'로 성공적인 거래를 저장할 수있는 다음과 같은

같은과 개체에 오류를 추가 할 수 있습니다 그 방법 유효성 검사기의 Stripe charge.

validate :card_validation 

def card_validation 

    begin 
     charge = Stripe::Charge.create(
      :customer => user.stripe_customer_id, 
      :amount => self.session.price.to_i * 100, 
      :description => "Registration for #{self.session.name} (Id:#{self.session.id})", 
      :currency => 'cad' 
     ) 
     etc etc 
    rescue => e 
     errors.add(:credit_card, e.message) 
     #Then you might have a model to log the transaction error. 
     Error.create(charge, customer) 
    end 

end 

이 방법 당신은 당신이 항목을 저장하는 대신에 빈 오류 메시지를 제공하거나, 스트라이프에서 모든 마지막 오류를 처리하지 않아도에서 얻을만한 다른 오류와 같은 오류를 처리 할 수 ​​있습니다.

+0

입력 해 주셔서 감사합니다. 레일스로 시작하기 전에 custom_validator에 대해 들어 본 적이 없었습니다. 따라서 올바르게 이해한다면 등록 모델의 메소드에 전체 Stripe 청구 로직을 넣어야합니까? 그렇다면 등록 컨트롤러는 어떻게됩니까? 플래시 오류가있는 사용자를 어떻게 리디렉션합니까? 죄송합니다 많은 질문에 대해, 여전히 혼란 :) –

+1

업데이트 100 % 정확하지만 일반적으로 생각하지 대답 – rovermicrover

+0

내가 생각, 내가 등록 모델은 데이터베이스에 저장 될 때마다, 유효성 검사 : card_validation가 호출됩니다 (조금 전에 필터처럼) 유효한 거래/카드 만 저장하십시오. 입력 해 주셔서 감사합니다! –

관련 문제