~singpolyma/jmp-pay

ref: f2b4acbb51f696a8ca5c617ce7a33f148459326b jmp-pay/config.ru -rw-r--r-- 1.6 KiB
f2b4acbbStephen Paul Weber Add magic comment 3 years 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
# frozen_string_literal: true

require "braintree"
require "delegate"
require "dhall"
require "redis"
require "roda"

REDIS = Redis.new
BRAINTREE_CONFIG = Dhall.load("env:BRAINTREE_CONFIG").sync

class CreditCardGateway
	def initialize(jid)
		@jid = jid

		@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 customer_id
		customer_id = REDIS.get(redis_key)
		return customer_id if customer_id

		cresult = @gateway.customer.create
		raise "Braintree customer create failed" unless cresult.success?

		result = REDIS.set(redis_key, cresult.customer.id)
		raise "Saving new customer to redis failed" unless result == "OK"

		cresult.customer.id
	end

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

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

protected

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

class JmpPay < Roda
	plugin :render, engine: "slim"
	plugin :common_logger, $stdout

	route do |r|
		r.on :jid do |jid|
			r.on "credit_cards" do
				gateway = CreditCardGateway.new(jid)

				r.get do
					view(
						"credit_cards",
						locals: {
							token: gateway.client_token
						}
					)
				end

				r.post do
					gateway.default_payment_method = request.params["braintree_nonce"]
					"OK"
				end
			end
		end
	end
end

run JmpPay.freeze.app