2019-10-13 18:52:43 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2019-12-03 19:23:45 -05:00
|
|
|
module DiscourseSubscriptions
|
2019-10-13 18:52:43 -04:00
|
|
|
class SubscriptionsController < ::ApplicationController
|
2019-12-03 19:23:45 -05:00
|
|
|
include DiscourseSubscriptions::Stripe
|
|
|
|
include DiscourseSubscriptions::Group
|
2019-10-13 18:52:43 -04:00
|
|
|
before_action :set_api_key
|
2019-10-28 20:43:32 -04:00
|
|
|
requires_login
|
|
|
|
|
|
|
|
def index
|
|
|
|
begin
|
2019-11-04 00:37:21 -05:00
|
|
|
products = ::Stripe::Product.list(active: true)
|
2019-10-28 20:43:32 -04:00
|
|
|
|
2019-11-04 00:37:21 -05:00
|
|
|
subscriptions = products[:data].map do |p|
|
|
|
|
{
|
|
|
|
id: p[:id],
|
|
|
|
description: p.dig(:metadata, :description)
|
|
|
|
}
|
|
|
|
end
|
2019-10-28 20:43:32 -04:00
|
|
|
|
|
|
|
render_json_dump subscriptions
|
|
|
|
|
|
|
|
rescue ::Stripe::InvalidRequestError => e
|
2019-12-11 17:59:38 -05:00
|
|
|
render_json_error e.message
|
2019-10-28 20:43:32 -04:00
|
|
|
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-11-12 18:19:49 -05:00
|
|
|
items: [ { plan: params[:plan] } ],
|
2019-11-12 22:21:21 -05:00
|
|
|
metadata: metadata_user,
|
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-12-03 19:23:45 -05:00
|
|
|
DiscourseSubscriptions::Customer.create(
|
2019-11-28 01:43:03 -05:00
|
|
|
user_id: current_user.id,
|
|
|
|
customer_id: params[:customer],
|
|
|
|
product_id: plan[:product]
|
|
|
|
)
|
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
|
2019-12-11 17:59:38 -05:00
|
|
|
render_json_error e.message
|
2019-10-16 21:07:06 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2019-11-12 22:21:21 -05:00
|
|
|
def metadata_user
|
|
|
|
{ user_id: current_user.id, username: current_user.username_lower }
|
|
|
|
end
|
|
|
|
|
2019-10-23 20:37:20 -04:00
|
|
|
def subscription_ok
|
|
|
|
['active', 'trialing'].include?(@subscription[:status])
|
2019-10-13 18:52:43 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|