discourse-subscriptions/app/controllers/patrons_controller.rb

79 lines
1.9 KiB
Ruby
Raw Normal View History

2019-09-11 19:11:02 +10:00
# frozen_string_literal: true
module DiscoursePatrons
2019-09-13 12:35:38 +10:00
class PatronsController < ::ApplicationController
2019-09-11 19:55:35 +10:00
skip_before_action :verify_authenticity_token, only: [:create]
2019-09-14 20:54:13 +10:00
before_action :set_api_key
2019-09-11 19:55:35 +10:00
2019-09-11 19:11:02 +10:00
def index
2019-09-13 12:58:17 +10:00
result = { email: '' }
2019-09-13 12:35:38 +10:00
if current_user
result[:email] = current_user.email
end
2019-09-11 19:11:02 +10:00
render json: result
end
2019-09-14 17:28:58 +10:00
def show
2019-09-15 08:40:52 +10:00
payment_intent = Stripe::PaymentIntent.retrieve(params[:pid])
if current_user && (current_user.admin || payment_intent[:customer] == current_user.id)
result = payment_intent
else
result = { error: 'Not found' }
end
2019-09-14 18:17:45 +10:00
render json: result
2019-09-14 17:28:58 +10:00
end
2019-09-11 19:11:02 +10:00
def create
2019-09-11 19:55:35 +10:00
begin
response = ::Stripe::PaymentIntent.create(
2019-09-12 11:49:52 +10:00
amount: param_currency_to_number,
2019-09-11 19:55:35 +10:00
currency: SiteSetting.discourse_patrons_currency,
payment_method_types: ['card'],
2019-09-13 14:34:06 +10:00
payment_method: params[:payment_method_id],
description: SiteSetting.discourse_patrons_payment_description,
2019-09-13 14:34:06 +10:00
receipt_email: params[:receipt_email],
2019-09-11 19:55:35 +10:00
confirm: true,
metadata: { user_id: user_id }
2019-09-11 19:55:35 +10:00
)
2019-09-13 22:03:29 +10:00
Payment.create(
2019-09-15 22:03:42 +10:00
user_id: response[:metadata][:user_id],
2019-09-13 22:03:29 +10:00
payment_intent_id: response[:id],
receipt_email: response[:receipt_email],
url: response[:charges][:url],
2019-09-14 15:55:25 +10:00
amount: response[:amount],
currency: response[:currency]
2019-09-13 22:03:29 +10:00
)
2019-09-11 19:55:35 +10:00
rescue ::Stripe::InvalidRequestError => e
response = { error: e }
rescue ::Stripe::CardError => e
response = { error: 'Card Declined' }
end
render json: response
2019-09-11 19:11:02 +10:00
end
2019-09-12 11:49:52 +10:00
private
2019-09-14 20:54:13 +10:00
def set_api_key
::Stripe.api_key = SiteSetting.discourse_patrons_secret_key
end
2019-09-12 11:49:52 +10:00
def param_currency_to_number
params[:amount].to_s.sub('.', '').to_i
end
2019-09-14 15:55:25 +10:00
def user_id
if current_user
current_user.id
end
end
2019-09-11 17:13:12 +10:00
end
end