~singpolyma/jmp-pay

jmp-pay/config.ru -rw-r--r-- 7.8 KiB
ed68f065Stephen Paul Weber small on next line 24 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# frozen_string_literal: true

require "braintree"
require "date"
require "delegate"
require "dhall"
require "pg"
require "redis"
require "roda"
require "uri"

if ENV["RACK_ENV"] == "development"
	require "pry-rescue"
	use PryRescue::Rack
end

require_relative "lib/electrum"

require "sentry-ruby"
Sentry.init do |config|
	config.traces_sample_rate = 1
end
use Sentry::Rack::CaptureExceptions

REDIS = Redis.new
PLANS = Dhall.load("env:PLANS").sync
BRAINTREE_CONFIG = Dhall.load("env:BRAINTREE_CONFIG").sync
ELECTRUM = Electrum.new(
	**Dhall::Coder.load("env:ELECTRUM_CONFIG", transform_keys: :to_sym)
)

DB = PG.connect(dbname: "jmp")
DB.type_map_for_results = PG::BasicTypeMapForResults.new(DB)
DB.type_map_for_queries = PG::BasicTypeMapForQueries.new(DB)

class Plan
	def self.for(plan_name)
		new(PLANS.find { |p| p[:name].to_s == plan_name })
	end

	def initialize(plan)
		@plan = plan
	end

	def price(months=1)
		(BigDecimal.new(@plan[:monthly_price].to_i) * months) / 10000
	end

	def currency
		@plan[:currency].to_s.to_sym
	end

	def merchant_account
		BRAINTREE_CONFIG[:merchant_accounts][currency]
	end

	def self.active?(customer_id)
		DB.exec_params(<<~SQL, [customer_id]).first&.[]("count").to_i > 0
			SELECT count(1) AS count FROM customer_plans
			WHERE customer_id=$1 AND expires_at > NOW()
		SQL
	end

	def activate(customer_id, months)
		DB.exec_params(
			"INSERT INTO plan_log VALUES ($1, $2, tsrange($3, $4))",
			[customer_id, @plan[:name], Time.now, Date.today >> months]
		)
		true
	end
end

class CreditCardGateway
	def initialize(jid, customer_id=nil)
		@jid = jid
		@customer_id = customer_id

		@gateway = Braintree::Gateway.new(
			environment: BRAINTREE_CONFIG[:environment].to_s,
			merchant_id: BRAINTREE_CONFIG[:merchant_id].to_s,
			public_key: BRAINTREE_CONFIG[:public_key].to_s,
			private_key: BRAINTREE_CONFIG[:private_key].to_s
		)
	end

	def check_customer_id(cid)
		return cid unless ENV["RACK_ENV"] == "production"

		raise "customer_id does not match" unless @customer_id == cid

		cid
	end

	def customer_id
		customer_id = REDIS.get(redis_key_jid)
		return customer_id if check_customer_id(customer_id)

		result = @gateway.customer.create
		raise "Braintree customer create failed" unless result.success?
		@customer_id = result.customer.id
		save_customer_id!
	end

	def save_customer_id!
		unless REDIS.set(redis_key_jid, @customer_id) == "OK"
			raise "Saving new jid,customer to redis failed"
		end

		unless REDIS.set(redis_key_customer_id, @jid) == "OK"
			raise "Saving new customer,jid to redis failed"
		end

		@customer_id
	end

	def client_token
		@gateway.client_token.generate(customer_id: customer_id)
	end

	def payment_methods?
		!@gateway.customer.find(customer_id).payment_methods.empty?
	end

	def default_payment_method=(nonce)
		@gateway.payment_method.create(
			customer_id: customer_id,
			payment_method_nonce: nonce,
			options: {
				make_default: true
			}
		)
	end

	def decline_guard(ip)
		customer_declines, ip_declines = REDIS.mget(
			"jmp_pay_decline-#{@customer_id}",
			"jmp_pay_decline-#{ip}"
		)
		customer_declines.to_i < 2 && ip_declines.to_i < 4
	end

	def sale(ip:, **kwargs)
		return false unless decline_guard(ip)
		result = @gateway.transaction.sale(**kwargs)
		return true if result.success?

		REDIS.incr("jmp_pay_decline-#{@customer_id}")
		REDIS.expire("jmp_pay_decline-#{@customer_id}", 60 * 60 * 24)
		REDIS.incr("jmp_pay_decline-#{ip}")
		REDIS.expire("jmp_pay_decline-#{ip}", 60 * 60 * 24)
		false
	end

	def buy_plan(plan_name, months, nonce, ip)
		plan = Plan.for(plan_name)
		sale(
			ip: ip,
			amount: plan.price(months),
			payment_method_nonce: nonce,
			merchant_account_id: plan.merchant_account,
			options: {submit_for_settlement: true}
		) && plan.activate(@customer_id, months)
	end

protected

	def redis_key_jid
		"jmp_customer_id-#{@jid}"
	end

	def redis_key_customer_id
		"jmp_customer_jid-#{@customer_id}"
	end
end

class UnknownTransactions
	def self.from(customer_id, address, tx_hashes)
		self.for(
			customer_id,
			fetch_rows_for(address, tx_hashes).map { |row| row["transaction_id"] }
		)
	end

	def self.fetch_rows_for(address, tx_hashes)
		values = tx_hashes.map do |tx_hash|
			"('#{DB.escape_string(tx_hash)}/#{DB.escape_string(address)}')"
		end
		return [] if values.empty?
		DB.exec_params(<<-SQL)
			SELECT transaction_id FROM
				(VALUES #{values.join(',')}) AS t(transaction_id)
				LEFT JOIN transactions USING (transaction_id)
			WHERE transactions.transaction_id IS NULL
		SQL
	end

	def self.for(customer_id, transaction_ids)
		transaction_ids.empty? ? None.new : new(customer_id, transaction_ids)
	end

	def initialize(customer_id, transaction_ids)
		@customer_id = customer_id
		@transaction_ids = transaction_ids
	end

	def enqueue!
		REDIS.hset(
			"pending_btc_transactions",
			*@transaction_ids.flat_map { |txid| [txid, @customer_id] }
		)
	end

	class None
		def enqueue!; end
	end
end

# This class must contain all of the routes because of how the DSL works
# rubocop:disable Metrics/ClassLength
class JmpPay < Roda
	SENTRY_DSN = ENV["SENTRY_DSN"] && URI(ENV["SENTRY_DSN"])
	plugin :render, engine: "slim"
	plugin :common_logger, $stdout

	def redis_key_btc_addresses
		"jmp_customer_btc_addresses-#{request.params['customer_id']}"
	end

	def verify_address_customer_id(r)
		return if REDIS.sismember(redis_key_btc_addresses, request.params["address"])

		warn "Address and customer_id do not match"
		r.halt([
			403,
			{"Content-Type" => "text/plain"},
			"Address and customer_id do not match"
		])
	end

	route do |r|
		r.on "electrum_notify" do
			verify_address_customer_id(r)

			UnknownTransactions.from(
				request.params["customer_id"],
				request.params["address"],
				ELECTRUM
					.getaddresshistory(request.params["address"])
					.map { |item| item["tx_hash"] }
			).enqueue!

			"OK"
		end

		r.on :jid do |jid|
			Sentry.set_user(id: request.params["customer_id"], jid: jid)

			gateway = CreditCardGateway.new(
				jid,
				request.params["customer_id"]
			)

			r.on "activate" do
				Sentry.configure_scope do |scope|
					scope.set_transaction_name("activate")
					scope.set_context(
						"activate",
						plan_name: request.params["plan_name"]
					)
				end

				render = lambda do |l={}|
					view(
						"activate",
						locals: {
							token: gateway.client_token,
							customer_id: gateway.customer_id,
							error: false
						}.merge(l)
					)
				end

				r.get do
					if Plan.active?(gateway.customer_id)
						r.redirect request.params["return_to"], 303
					else
						render.call
					end
				end

				r.post do
					result = DB.transaction do
						Plan.active?(gateway.customer_id) || gateway.buy_plan(
							request.params["plan_name"],
							5,
							request.params["braintree_nonce"],
							request.ip
						)
					end
					if request.params["auto_top_up_amount"].to_i >= 15
						REDIS.set(
							"jmp_customer_auto_top_up_amount-#{gateway.customer_id}",
							request.params["auto_top_up_amount"].to_i
						)
					end
					if result
						r.redirect request.params["return_to"], 303
					else
						render.call(error: true)
					end
				end
			end

			r.on "credit_cards" do
				r.get do
					view(
						"credit_cards",
						locals: {
							token: gateway.client_token,
							customer_id: gateway.customer_id,
							auto_top_up: REDIS.get(
								"jmp_customer_auto_top_up_amount-#{gateway.customer_id}"
							) || (gateway.payment_methods? ? "" : "15")
						}
					)
				end

				r.post do
					gateway.default_payment_method = request.params["braintree_nonce"]
					if request.params["auto_top_up_amount"].to_i >= 15
						REDIS.set(
							"jmp_customer_auto_top_up_amount-#{gateway.customer_id}",
							request.params["auto_top_up_amount"].to_i
						)
					elsif request.params["auto_top_up_amount"].to_i == 0
						REDIS.del(
							"jmp_customer_auto_top_up_amount-#{gateway.customer_id}"
						)
					end
					"OK"
				end
			end
		end
	end
end
# rubocop:enable Metrics/ClassLength

run JmpPay.freeze.app