неопределенный метод `stripe_id 'для nil: NilClass - PullRequest
0 голосов
/ 26 февраля 2019

У меня возникла эта проблема, и каждый раз, когда я просто удаляю stripe_id, у меня не появляется ошибка, но я возвращаюсь на домашнюю страницу без работающего платежа ... Некоторые фрилансеры сделали эту часть, и я не могу понять,почему он не работает на моем компьютере, но отлично работает на сервере или компьютере фрилансера ... код не будет работать ни на одном из моих компьютеров ... Кто-нибудь знает, в чем проблема, которую я пытался выяснить на этом.На сервере платеж работает ...

Это мой контроллер

class SubscriptionsController < ApplicationController
  protect_from_forgery :except => :webhooks
  before_action :authenticate_user!, except: [:webhooks]

  def new
  end

  # this is for recursive
  def subscription_payment
    begin
      stripe_id = Plan.find_by_plan_type(params[:plan_type]).stripe_id
      # stripe_id = Plan.find(params[:plan_id]).stripe_id
      @plan = Stripe::Plan.retrieve(stripe_id)
      customer = Stripe::Customer.create(
        :description => "Customer for #{params[:stripeEmail]}",
        :source => params[:stripeToken],
        :email => params[:stripeEmail]
      )

      stripe_subscription = customer.subscriptions.create(:plan => @plan.id)
      @payment = current_user.payments.new(customer_id: customer.id, card_exp_month: customer.sources[:data][0]['exp_month'], card_exp_year: customer.sources[:data][0]['exp_year'], card_id: customer.sources[:data][0].id, customer_subscription_id: stripe_subscription.id, plan_id: @plan.id)
      @payment.save!

      if params[:plan_type] == "monthly"
        current_user.build_user_plan(plan_id: @plan.id, plan_expiry: Date.today+1.months).save
      elsif params[:plan_type] == "annual"
        current_user.build_user_plan(plan_id: @plan.id, plan_expiry: Date.today+1.years).save
      else
        current_user.build_user_plan(plan_id: @plan.id).save
      end

      flash[:notice] = 'You have successfully got the premium.'
        redirect_to root_path
    rescue Stripe::StripeError => e
      flash[:error] = e.message
      redirect_to root_path
    end
  end

  # Method responsbile for handling stripe webhooks
  # reference https://stripe.com/docs/webhooks
  def webhooks
    begin
      event_json = JSON.parse(request.body.read)
      event_object = event_json['data']['object']
      #refer event types here https://stripe.com/docs/api#event_types
      case event_json['type']
        # when 'invoice.payment_succeeded'
        #   handle_success_invoice event_object
        # when 'invoice.payment_failed'
        #   handle_failure_invoice event_object
        # when 'charge.failed'
        #   handle_failure_charge event_object
        when 'customer.subscription.deleted'
        when 'customer.subscription.updated'
      end
    rescue Exception => ex
      render :json => {:status => 422, :error => "Webhook call failed"}
      return
    end
    render :json => {:status => 200}
  end

end

Это моя кнопка входа, с которой начисляется сумма.

                    <% if user_signed_in? %>
                      <%= form_tag subscription_payment_path, method: :post do %>
                        <%= hidden_field_tag :plan_type, "monthly" %>
                        <script class="stripe-button"
                          data-amount="1000"

                          data-currency="CAD"

                          data-email="<%= current_user.email %>"

                          data-key="<%= Rails.configuration.stripe[:publishable_key] %>"

                          src="https://checkout.stripe.com/checkout.js">
                        </script>
                      <% end %>
                    <% else %>
                      <a href="/users/sign_in" class="btn btn-neutral btn-round">
                        Subscribe
                      </a>
                    <% end %>

1 Ответ

0 голосов
/ 26 февраля 2019

Если вы видите undefined method 'stripe_id' for nil:NilClass, то это означает, что Plan.find_by_plan_type(params[:plan_type]) скорее всего вернет nil.И вы не можете получить stripe_id из nil.

Вы уверены, что у вас есть записи базы данных на вашем локальном компьютере, в частности Plan записей с plan_type?

Если вы хотите обработать сценарий, в котором Plan не найден, учитывая plan_type, то вы можете попробовать:

plan = Plan.find_by_plan_type(params[:plan_type])
raise SomeSortOfError if plan.nil? # make sure to rescue accordingly
stripe_id = plan.stripe_id
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...