полоса отменить подписку после окончания периода - PullRequest
0 голосов
/ 27 июня 2018

У меня есть способ отменить подписку следующим образом:

def cancel_subscription
  customer = Stripe::Customer.retrieve(current_user.stripe_customer_id)
  customer.subscriptions.retrieve(current_user.subscription_id).delete(:at_period_end => true)
  current_user.subscribed = false
  if current_user.save
    redirect_to root_path
  end
end

Я использую (:at_period_end => true) для отмены в конце на дату окончания с начала.

Но также в моей БД у меня есть столбец, который имеет значение false или true в зависимости от того, подписан клиент или нет:

current_user.subscribed = false

Я хочу изменить это на false после окончания периода. Например, клиент отменяет подписку, но у него остается 10 дней. Я хочу, чтобы current_user.subscribed был установлен в false после истечения фактического периода, и теперь клиент правильно отписался.

Вот настройка веб-хука:

def webhook
  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

В моем файле маршрутов для полосы есть следующее:

Rails.application.routes.draw do
  root to: 'welcome#index'
  devise_for :users, controllers: { sessions: 'users/sessions',
                                    :omniauth_callbacks => "callbacks",
                                    registrations: "users/registrations"}
  resources :profiles
  resources :subscriptions, only: [:new, :create]
  resources :topics, only: [:index, :edit, :create, :destroy, :update]
  resources :topic_profiles, only: [:create, :destroy]
  resources :chats, only: [:index]

  #resources :messages, only: %i[new edit]
  resources :messages, only: %i[new create index]
  post 'incoming_message/webhook'
  resources :test_inbound_messages, only: %i[new create]


  post 'subscription_checkout' => 'subscriptions#subscription_checkout'
  post 'webhook' => 'subscriptions#webhook'
  get 'plans' => 'subscriptions#plans'
  post 'cancel_subscription' => 'subscriptions#cancel_subscription'
  get 'get_cities' => 'profiles#get_cities'
  get 'turn_off_modal'=> "profiles#turn_off_modal"
end

Я забыл настроить веб-хуки на панели инструментов полосы, он запрашивает у меня URL (URL to be called) для ввода, в соответствии с этими маршрутами, каким должен быть URL? я не уверен, что использовать здесь?

1 Ответ

0 голосов
/ 27 июня 2018

Ручка в case из customer.subscription.deleted, смотрите ниже:

def webhook
  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'
        # NOTE HERE, this event will come when stripe actually marks the subscription as canceled, which in your example will be 10 days later.
        # so simply get the user here and mark `subscribed` as false, instead of doing it early
        user = Stripe::Customer.retrieve(event_object['customer'])
        user.update_attribute :subscribed, false
      when 'customer.subscription.updated'
    end
  rescue Exception => ex
    render :json => {:status => 422, :error => "Webhook call failed"}
    return
  end
  render :json => {:status => 200}
end
...