Skip to content

Instantly share code, notes, and snippets.

@bearded-avenger
Created September 24, 2020 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bearded-avenger/68fa43fcdee3e6c641df3d9048dbb872 to your computer and use it in GitHub Desktop.
Save bearded-avenger/68fa43fcdee3e6c641df3d9048dbb872 to your computer and use it in GitHub Desktop.
module TenantServices
class SubscriptionServicePaypal
def initialize(params)
@subscription = params[:subscription]
@coupon = params[:coupon]
@paypal_token = params[:paypal_token]
@plan = @subscription.subscription_plan
@customer = @subscription.customer
@site = @subscription.site
end
def call
# create or find customer
customer ||= TenantServices::BraintreeCustomerService.new({customer: @subscription.customer,payment_method_nonce: @paypal_token }).call
if customer && customer.success?
subscription ||= create_subscription(customer.payload)
if subscription && subscription.success?
@subscription.update_attributes(
status: subscription.payload.status,
braintree_id: subscription.payload.id,
expiration: set_expiration(subscription.payload)
)
handle_success(subscription.payload)
else
handle_error(subscription&.error)
end
else
handle_error(customer&.error)
end
end
end
private
attr_reader :subscription, :coupon, :paypal_token, :plan, :customer, :site
def create_subscription(customer_result)
result ||= BraintreeServices::CreateSubscription.new({site: site,
subscription_params: subscription_params(customer_result)
}).call
result && result.success? ? result.payload : handle_error(result.error)
end
def subscription_params(customer_result)
{
payment_method_token: customer_result.payment_methods[0].token,
plan_id: plan.braintree_id
}
end
def set_expiration(payload)
t = subscription.trial_period == true ? subscription.first_billing_date : subscription.billing_period_end_date
Time.at(t).to_datetime
end
def handle_success(payload)
OpenStruct.new({success?:true, payload: payload})
end
def handle_error(error)
OpenStruct.new({success?:false, error: error})
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment