credit_card_customer_gateway.rb

 1# frozen_string_literal: true
 2
 3require_relative "credit_card_gateway"
 4
 5class CreditCardCustomerGateway
 6	def initialize(jid, customer_id, antifraud, currency: nil)
 7		@jid = jid
 8		@customer_id = customer_id
 9		@gateway = CreditCardGateway.new(
10			currency || customer_plan&.dig(:currency),
11			antifraud
12		)
13	end
14
15	def merchant_account
16		@gateway.merchant_account
17	end
18
19	def check_customer_id(cid)
20		return cid unless ENV["RACK_ENV"] == "production"
21
22		raise "customer_id does not match" unless @customer_id == cid
23
24		cid
25	end
26
27	def customer_id
28		customer_id = Customer.new(nil, @jid).customer_id
29		return customer_id if check_customer_id(customer_id)
30
31		result = @gateway.customer.create
32		raise "Braintree customer create failed" unless result.success?
33
34		@customer_id = result.customer.id
35		Customer.new(@customer_id, @jid).save!
36		@customer_id
37	end
38
39	def customer_plan
40		name = DB.exec_params(<<~SQL, [@customer_id]).first&.[]("plan_name")
41			SELECT plan_name FROM customer_plans WHERE customer_id=$1 LIMIT 1
42		SQL
43		PLANS.find { |plan| plan[:name].to_s == name }
44	end
45
46	def client_token
47		@gateway.client_token(customer_id: customer_id)
48	end
49
50	def payment_methods?
51		!@gateway.customer.find(customer_id).payment_methods.empty?
52	end
53
54	def antifraud
55		return if REDIS.exists?("jmp_antifraud_bypass-#{customer_id}")
56
57		@gateway.antifraud
58	end
59
60	def with_antifraud(&blk)
61		@gateway.with_antifraud(&blk)
62	end
63
64	def sale(nonce, amount)
65		customer = Customer.new(@customer_id, @jid)
66		raise "Please contact JMP support." if customer.trust_level == "Tombed"
67
68		@gateway.sale(nonce, amount, customer_id: customer_id)
69	end
70
71	def default_method(nonce)
72		with_antifraud do
73			@gateway.payment_method.create(
74				customer_id: customer_id, payment_method_nonce: nonce,
75				options: {
76					verify_card: true, make_default: true,
77					verification_merchant_account_id: merchant_account.to_s
78				}
79			)
80		end
81	end
82
83	def remove_method(token)
84		@gateway.payment_method.delete(token)
85	end
86end