discourse-subscriptions/app/controllers/subscriptions_controller.rb

63 lines
1.5 KiB
Ruby
Raw Normal View History

2019-10-13 18:52:43 -04:00
# frozen_string_literal: true
module DiscoursePatrons
class SubscriptionsController < ::ApplicationController
include DiscoursePatrons::Stripe
before_action :set_api_key
2019-10-28 20:43:32 -04:00
requires_login
def index
begin
customer = DiscoursePatrons::Customer.find_user(current_user)
if customer.present?
subscriptions = ::Stripe::Subscription.list(customer: customer.customer_id)
else
subscriptions = []
end
render_json_dump subscriptions
rescue ::Stripe::InvalidRequestError => e
return render_json_error e.message
end
end
2019-10-13 18:52:43 -04:00
def create
2019-10-16 21:07:06 -04:00
begin
2019-10-23 20:37:20 -04:00
plan = ::Stripe::Plan.retrieve(params[:plan])
@subscription = ::Stripe::Subscription.create(
2019-10-16 21:07:06 -04:00
customer: params[:customer],
2019-10-23 20:37:20 -04:00
items: [ { plan: params[:plan] } ]
2019-10-16 21:07:06 -04:00
)
2019-10-23 20:37:20 -04:00
group = plan_group(plan)
if subscription_ok && group
2019-10-16 21:07:06 -04:00
group.add(current_user)
end
2019-10-28 23:15:13 -04:00
unless DiscoursePatrons::Customer.exists?(user_id: current_user.id)
DiscoursePatrons::Customer.create(user_id: current_user.id, customer_id: params[:customer])
end
2019-10-27 23:48:59 -04:00
2019-10-23 20:37:20 -04:00
render_json_dump @subscription
2019-10-16 21:07:06 -04:00
rescue ::Stripe::InvalidRequestError => e
return render_json_error e.message
end
end
private
2019-10-23 20:37:20 -04:00
def plan_group(plan)
Group.find_by_name(plan[:metadata][:group_name])
end
def subscription_ok
['active', 'trialing'].include?(@subscription[:status])
2019-10-13 18:52:43 -04:00
end
end
end