contagorda-pay 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: d2916fad01487c6b0a61405fffa823b9394c6517a6cfde80c87a9661bef5a2d6
4
+ data.tar.gz: 583ae68a23eea804dcdd03e989a9fbd79373bd40b61d37a88cbe754af18d4b4f
5
+ SHA512:
6
+ metadata.gz: 5f4ac5ad6956fe1a286dae72ff1ad8065009b67974f10b48e6167638512f930d600c216a68611e233861fcaa3ca374ae5aeee357c7a59395961d0624dc563196
7
+ data.tar.gz: bab0fb82f2cefa7561a5dfe4a6f04e3ba29c7bdce7fd521d6999c8514297e89d873cbe30b3cd77820b4338338c89268ffb2317aeee3de569673aeb3cdca982b0
data/CHANGELOG.md ADDED
@@ -0,0 +1,25 @@
1
+ # Changelog
2
+
3
+ All notable changes to the `contagorda-pay` gem. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the gem uses
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## 0.1.0 - 2026-10-29
10
+
11
+ ### Added
12
+
13
+ - `ContaGorda::Pay::Client`: `connect`, `session`, `subscription`,
14
+ `cancel_subscription` and `resume_subscription`, authenticated with the app
15
+ key. `connect` always sends an `Idempotency-Key`.
16
+ - `ContaGorda::Pay::Webhook`: verifies `X-Pay-Signature` on the raw body, with
17
+ a 5-minute limit, and answers a typed `Event`.
18
+ - `ContaGorda::Pay::Webhook::Endpoint`: a Rack endpoint for Rails, Sinatra or
19
+ `config.ru` that calls the app's handler with the verified event.
20
+ - `ContaGorda::Pay::ReturnToken`: verifies the `pay_token` on the return from
21
+ the checkout (HS256, issuer `pay`, bound to the session).
22
+ - `ContaGorda::Pay::Testing`: signed payloads, headers and return tokens for
23
+ the app's own tests.
24
+ - Configuration from `PAY_SECRET_KEY`, `PAY_WEBHOOK_SECRET` and `PAY_URL`, or
25
+ `ContaGorda::Pay.configure`.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thadeu Esteves Jr
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,221 @@
1
+ # contagorda-pay
2
+
3
+ Ruby SDK for the ContaGorda Pay broker. Your app sends one request to open a
4
+ checkout and hears back by signed webhook. It never learns which gateway took
5
+ the money.
6
+
7
+ - No runtime dependencies (standard library only)
8
+ - Ruby 3.0 and up
9
+ - Rails, Sinatra, Hanami or plain Rack
10
+
11
+ Billing stays in your app: plans, limits, invoices and what a payment unlocks
12
+ are yours. The gem only formalizes the payment.
13
+
14
+ ## Install
15
+
16
+ ```ruby
17
+ gem 'contagorda-pay'
18
+ ```
19
+
20
+ Set two values from the broker's dashboard (Apps → your app):
21
+
22
+ ```sh
23
+ PAY_SECRET_KEY=sk_app_live_... # the app key
24
+ PAY_WEBHOOK_SECRET=pwhsec_... # the webhook endpoint's signing secret
25
+ # PAY_URL=https://pay.contagorda.com (the default)
26
+ ```
27
+
28
+ That is all the configuration. To set it in code instead:
29
+
30
+ ```ruby
31
+ ContaGorda::Pay.configure do |config|
32
+ config.secret_key = Rails.application.credentials.pay_secret_key
33
+ config.webhook_secret = Rails.application.credentials.pay_webhook_secret
34
+ end
35
+ ```
36
+
37
+ ## 1. Open a checkout
38
+
39
+ ```ruby
40
+ pay = ContaGorda::Pay::Client.new
41
+
42
+ checkout = pay.connect(
43
+ amount: '19.00',
44
+ currency: 'USD',
45
+ interval: 'month', # subscriptions only
46
+ return_to: billing_return_url,
47
+ customer: {external_ref: account.id, email: user.email, name: account.name},
48
+ metadata: {plan: 'standard'},
49
+ idempotency_key: "upgrade-#{account.id}-#{params[:form_token]}"
50
+ )
51
+
52
+ redirect_to checkout.redirect_url, allow_other_host: true
53
+ ```
54
+
55
+ `customer[external_ref]` is your own id for the customer. Every webhook about
56
+ this payment carries it back as `event.customer_ref`.
57
+
58
+ Pass a stable `idempotency_key`, so a double click opens one checkout and not
59
+ two. When you leave it out, the gem sends a random one.
60
+
61
+ To change plans, send `replaces: current_subscription_id`. The broker cancels
62
+ the old subscription when the new one is active. If the customer leaves the
63
+ checkout, the old one keeps running.
64
+
65
+ ## 2. Receive webhooks
66
+
67
+ Mount the endpoint. It checks the signature and calls your block with the
68
+ event:
69
+
70
+ ```ruby
71
+ # config/routes.rb
72
+ post '/webhooks/pay', to: ContaGorda::Pay::Webhook::Endpoint.new { |event| Billing::PayWebhook.call(event) }
73
+ ```
74
+
75
+ ```ruby
76
+ class Billing::PayWebhook
77
+ def self.call(event)
78
+ account = Account.find_by(id: event.customer_ref)
79
+
80
+ return unless account
81
+
82
+ case event.type
83
+ when 'subscription.activated'
84
+ account.update!(plan: event.metadata.plan, pay_subscription_id: event.subscription.id)
85
+ when 'subscription.canceled'
86
+ account.update!(plan: 'free', pay_subscription_id: nil) if account.pay_subscription_id == event.subscription.id
87
+ end
88
+ end
89
+ end
90
+ ```
91
+
92
+ The endpoint answers:
93
+
94
+ | Case | Status | The broker |
95
+ |---|---|---|
96
+ | Your block returns | 200 | stops |
97
+ | Your block raises | 500 (the error goes to your error tracker) | retries |
98
+ | Bad or old signature | 401 | retries |
99
+ | Body is not an event | 400 | stops |
100
+
101
+ Sinatra or `config.ru`:
102
+
103
+ ```ruby
104
+ map('/webhooks/pay') { run ContaGorda::Pay::Webhook::Endpoint.new(Billing::PayWebhook) }
105
+ ```
106
+
107
+ In a controller of your own, use the verifier directly. Give it the raw body,
108
+ not parsed params:
109
+
110
+ ```ruby
111
+ event = ContaGorda::Pay::Webhook.new.event(request.raw_post, request.headers['X-Pay-Signature'])
112
+ ```
113
+
114
+ ### The rules that matter
115
+
116
+ 1. **Change what the customer has only from a webhook.** The return from the
117
+ checkout is for the message on the screen (see 3).
118
+ 2. **The same event can arrive more than once.** The broker retries until it
119
+ gets a 2xx. Make the handler idempotent: "set plan X" is already idempotent.
120
+ Where it is not, store `event.id` with a unique index in a table you
121
+ already have, and stop when the insert finds it there:
122
+
123
+ ```ruby
124
+ ActiveRecord::Base.transaction do
125
+ inserted = ProcessedEvent.insert_all([{event_id: event.id}], unique_by: :event_id, returning: :id)
126
+
127
+ apply(event) if inserted.any?
128
+ end
129
+ ```
130
+
131
+ 3. **An old subscription's events must not change the customer.** After a
132
+ plan change, the replaced subscription sends `subscription.canceled`. Before
133
+ you downgrade, compare `event.subscription.id` with the one you stored.
134
+
135
+ ### Events
136
+
137
+ | Type | `event.object` |
138
+ |---|---|
139
+ | `session.paid`, `session.failed`, `session.expired`, `session.refunded` | `event.session` |
140
+ | `subscription.activated`, `subscription.renewed`, `subscription.past_due`, `subscription.canceling`, `subscription.resumed`, `subscription.canceled` | `event.subscription` |
141
+ | `ping` (the dashboard's test button) | none |
142
+
143
+ Every event has `id`, `type`, `created_at`, `livemode?`, `customer_ref` and
144
+ `metadata`. Read any field as a method or by key: `event.subscription.cancel_at`,
145
+ `event.session[:amount]`. A field named like a Ruby method is read by key:
146
+ `event.session[:method]`.
147
+
148
+ ## 3. Show the result when the customer comes back
149
+
150
+ The broker sends the customer to `return_to` with `?session_id=…&pay_token=…`:
151
+
152
+ ```ruby
153
+ claims = ContaGorda::Pay::ReturnToken.new.verify(params[:pay_token], session_id: params[:session_id])
154
+
155
+ case claims&.status
156
+ when 'paid' then redirect_to billing_path, notice: 'Payment received. Your plan updates in a few seconds.'
157
+ when 'pending', 'processing' then redirect_to billing_path, notice: 'Payment in progress.'
158
+ else redirect_to billing_path, alert: 'The payment did not go through.'
159
+ end
160
+ ```
161
+
162
+ The token is signed with your app key, so nobody can forge it. But the browser
163
+ carries it and can send it again until it expires. Use it for the message, not
164
+ to grant anything.
165
+
166
+ ## 4. Subscriptions
167
+
168
+ ```ruby
169
+ pay.subscription(id) # read
170
+ pay.cancel_subscription(id) # at the end of the paid period
171
+ pay.cancel_subscription(id, at_period_end: false) # now
172
+ pay.resume_subscription(id) # take back a scheduled cancellation
173
+ pay.session(id) # read a payment
174
+ ```
175
+
176
+ Cancel and resume answer at once. The final state arrives by webhook
177
+ (`subscription.canceling`, `subscription.canceled`, `subscription.resumed`).
178
+
179
+ ## Errors
180
+
181
+ Everything the gem raises is a `ContaGorda::Pay::Error`:
182
+
183
+ | Error | When |
184
+ |---|---|
185
+ | `ConfigurationError` | no secret key or webhook secret |
186
+ | `ConnectionError` | the broker could not be reached |
187
+ | `AuthenticationError` (401), `PermissionError` (403), `NotFoundError` (404), `InvalidRequestError` (422), `GatewayError` (502), `APIError` (others) | the broker refused; `error.status`, `error.body`, and `error.errors` (one message per field) |
188
+ | `SignatureError`, `InvalidPayloadError` | a webhook that does not verify; the endpoint turns them into 401 and 400 |
189
+
190
+ ```ruby
191
+ rescue ContaGorda::Pay::Error => e
192
+ redirect_to billing_path, alert: 'The checkout could not be opened. Try again in a moment.'
193
+ ```
194
+
195
+ ## Testing your app
196
+
197
+ ```ruby
198
+ require 'contagorda/pay/testing'
199
+
200
+ body = ContaGorda::Pay::Testing.payload('subscription.activated', subscription: {
201
+ id: 'sub_1', metadata: {plan: 'pro'}, customer: {external_ref: account.id}
202
+ })
203
+
204
+ post '/webhooks/pay', params: body, headers: ContaGorda::Pay::Testing.headers(body)
205
+
206
+ token = ContaGorda::Pay::Testing.return_token(session_id: 'ses_1', status: 'paid')
207
+ get billing_return_path(session_id: 'ses_1', pay_token: token)
208
+ ```
209
+
210
+ The helpers sign with `PAY_WEBHOOK_SECRET` and `PAY_SECRET_KEY`, or with
211
+ `secret:` and `secret_key:`.
212
+
213
+ ## Development
214
+
215
+ ```sh
216
+ bundle exec rake # rspec + rubocop
217
+ COVERAGE=1 bundle exec rspec
218
+ ```
219
+
220
+ Releases: bump `lib/contagorda/pay/version.rb` and `CHANGELOG.md`, commit, then
221
+ `bundle exec rake tag`. The tag `contagorda-pay-vX.Y.Z` publishes the gem.
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/contagorda/pay/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'contagorda-pay'
7
+ spec.version = ContaGorda::Pay::VERSION
8
+ spec.authors = ['Thadeu Esteves Jr']
9
+
10
+ spec.summary = 'Ruby SDK for the ContaGorda Pay broker'
11
+ spec.description = 'Open a checkout, read and cancel subscriptions, verify the signed return and receive ' \
12
+ 'signed webhooks from the Pay broker. Standard library only: no runtime dependencies. Ruby 3.0 and up. ' \
13
+ 'Works in Rails, Sinatra, Hanami or plain Rack.'
14
+ spec.homepage = 'https://pay.contagorda.com/docs'
15
+ spec.license = 'MIT'
16
+ spec.required_ruby_version = '>= 3.0'
17
+
18
+ spec.metadata = {
19
+ 'rubygems_mfa_required' => 'true',
20
+ 'documentation_uri' => 'https://pay.contagorda.com/docs',
21
+ 'source_code_uri' => 'https://github.com/thadeu/contagorda-pay/tree/main/gems/contagorda-pay',
22
+ 'changelog_uri' => 'https://github.com/thadeu/contagorda-pay/blob/main/gems/contagorda-pay/CHANGELOG.md'
23
+ }
24
+
25
+ spec.files = Dir.chdir(__dir__) do
26
+ Dir['README.md', 'CHANGELOG.md', 'LICENSE', 'contagorda-pay.gemspec', 'lib/**/*.rb']
27
+ end
28
+
29
+ spec.require_paths = ['lib']
30
+
31
+ spec.add_development_dependency 'rack', '>= 2.2'
32
+ spec.add_development_dependency 'rake', '>= 13.0'
33
+ spec.add_development_dependency 'rspec', '>= 3.13', '< 4.0'
34
+ spec.add_development_dependency 'simplecov', '>= 0.22'
35
+ spec.add_development_dependency 'standard', '>= 1.0'
36
+ spec.add_development_dependency 'webmock', '>= 3.23'
37
+ end
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ContaGorda
4
+ module Pay
5
+ # The broker's API, authenticated with the app's secret key. The key never
6
+ # leaves the server: call this from the backend only.
7
+ #
8
+ # @example
9
+ # pay = ContaGorda::Pay::Client.new
10
+ #
11
+ # checkout = pay.connect(
12
+ # amount: '19.00', currency: 'USD', interval: 'month',
13
+ # return_to: 'https://app.example.com/billing/return',
14
+ # customer: {external_ref: account.id, email: user.email},
15
+ # metadata: {plan: 'standard'}
16
+ # )
17
+ #
18
+ # redirect_to checkout.redirect_url, allow_other_host: true
19
+ class Client
20
+ NETWORK_ERRORS = [
21
+ Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::ECONNABORTED, Errno::EHOSTUNREACH,
22
+ Errno::ENETUNREACH, Errno::EPIPE, Errno::ETIMEDOUT, Net::OpenTimeout, Net::ReadTimeout,
23
+ OpenSSL::SSL::SSLError, SocketError, IOError, EOFError
24
+ ].freeze
25
+
26
+ attr_reader :url
27
+
28
+ # Arguments win over {Pay.configure}, which wins over PAY_SECRET_KEY / PAY_URL.
29
+ def initialize(secret_key: nil, url: nil, open_timeout: nil, read_timeout: nil)
30
+ config = Pay.configuration
31
+
32
+ @secret_key = secret_key || config.secret_key
33
+ @url = (url || config.url).to_s.chomp('/')
34
+ @open_timeout = open_timeout || config.open_timeout
35
+ @read_timeout = read_timeout || config.read_timeout
36
+
37
+ raise ConfigurationError, 'no secret key: pass secret_key: or set PAY_SECRET_KEY' if @secret_key.to_s.empty?
38
+ end
39
+
40
+ # Creates what the app's Charges setting says, a one-off payment or a
41
+ # subscription, and answers where to send the customer (+redirect_url+).
42
+ #
43
+ # The broker requires an Idempotency-Key; a random one is sent when none
44
+ # is given. Pass a stable one (an order id, a form token) so a double
45
+ # click opens one checkout, not two.
46
+ #
47
+ # @param params [Hash] amount, currency, return_to, customer, and for a
48
+ # subscription interval; optional description, metadata, replaces
49
+ # @return [Resource] id, kind, status, redirect_url
50
+ def connect(idempotency_key: nil, **params)
51
+ request(:post, '/connect', body: params, idempotency_key: idempotency_key || SecureRandom.uuid)
52
+ end
53
+
54
+ # @return [Resource] the payment session
55
+ def session(id) = request(:get, "/api/v1/sessions/#{escape(id)}")
56
+
57
+ # @return [Resource] the subscription
58
+ def subscription(id) = request(:get, "/api/v1/subscriptions/#{escape(id)}")
59
+
60
+ # Ends the subscription at the end of the paid period, or now with
61
+ # +at_period_end: false+. The broker answers at once; the outcome
62
+ # arrives as subscription.canceling and subscription.canceled.
63
+ #
64
+ # @return [Resource] id, status, cancel_requested_at, cancel_at
65
+ def cancel_subscription(id, at_period_end: true)
66
+ request(:post, "/api/v1/subscriptions/#{escape(id)}/cancel", body: {at_period_end: at_period_end})
67
+ end
68
+
69
+ # Takes back a cancellation scheduled for the end of the period. The same
70
+ # subscription keeps renewing; nothing is charged now.
71
+ #
72
+ # @return [Resource] the subscription, with cancel_at nil
73
+ def resume_subscription(id) = request(:post, "/api/v1/subscriptions/#{escape(id)}/resume")
74
+
75
+ def inspect = "#<#{self.class.name} url=#{@url.inspect}>"
76
+
77
+ private
78
+
79
+ def escape(id) = URI.encode_www_form_component(id.to_s).gsub('+', '%20')
80
+
81
+ def request(method, path, body: nil, idempotency_key: nil)
82
+ uri = URI("#{@url}#{path}")
83
+ req = (method == :post) ? Net::HTTP::Post.new(uri) : Net::HTTP::Get.new(uri)
84
+
85
+ req['Accept'] = 'application/json'
86
+ req['Authorization'] = "Bearer #{@secret_key}"
87
+ req['User-Agent'] = "contagorda-pay-ruby/#{VERSION}"
88
+ req['Idempotency-Key'] = idempotency_key if idempotency_key
89
+
90
+ if body
91
+ req['Content-Type'] = 'application/json'
92
+ req.body = JSON.generate(body)
93
+ end
94
+
95
+ response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https',
96
+ open_timeout: @open_timeout, read_timeout: @read_timeout) { |http| http.request(req) }
97
+
98
+ parse(response)
99
+ rescue *NETWORK_ERRORS => e
100
+ raise ConnectionError, "could not reach #{@url}: #{e.class}: #{e.message}"
101
+ end
102
+
103
+ def parse(response)
104
+ text = response.body.to_s
105
+
106
+ json = begin
107
+ text.empty? ? {} : JSON.parse(text)
108
+ rescue JSON::ParserError
109
+ {'raw' => text}
110
+ end
111
+
112
+ raise APIError.for(response.code.to_i, json) unless response.is_a?(Net::HTTPSuccess)
113
+
114
+ Resource.wrap(json)
115
+ end
116
+ end
117
+ end
118
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ContaGorda
4
+ module Pay
5
+ # Defaults for every client. A value set here wins; otherwise the
6
+ # environment is read when the value is asked for, not at boot.
7
+ #
8
+ # PAY_SECRET_KEY the app key (sk_app_live_… or sk_app_test_…)
9
+ # PAY_WEBHOOK_SECRET the webhook endpoint's signing secret (pwhsec_…)
10
+ # PAY_URL the broker, https://pay.contagorda.com by default
11
+ class Configuration
12
+ DEFAULT_URL = 'https://pay.contagorda.com'
13
+
14
+ attr_writer :secret_key, :webhook_secret, :url
15
+ attr_accessor :open_timeout, :read_timeout
16
+
17
+ def initialize
18
+ @open_timeout = 5
19
+ @read_timeout = 20
20
+ end
21
+
22
+ def secret_key = present(@secret_key) || present(ENV['PAY_SECRET_KEY'])
23
+
24
+ def webhook_secret = present(@webhook_secret) || present(ENV['PAY_WEBHOOK_SECRET'])
25
+
26
+ def url = present(@url) || present(ENV['PAY_URL']) || DEFAULT_URL
27
+
28
+ def inspect = "#<#{self.class.name} url=#{url.inspect} secret_key=#{secret_key ? '[set]' : 'nil'}>"
29
+
30
+ private
31
+
32
+ def present(value)
33
+ value = value.to_s.strip
34
+
35
+ value.empty? ? nil : value
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ContaGorda
4
+ module Pay
5
+ # Everything the gem raises.
6
+ class Error < StandardError; end
7
+
8
+ # A key or a secret is missing, or an argument cannot be used.
9
+ class ConfigurationError < Error; end
10
+
11
+ # The broker could not be reached: DNS, connect, TLS or a timeout.
12
+ class ConnectionError < Error; end
13
+
14
+ # X-Pay-Signature is missing, malformed, too old, or does not match the body.
15
+ class SignatureError < Error; end
16
+
17
+ # A webhook body that is not a JSON event with an id and a type.
18
+ class InvalidPayloadError < Error; end
19
+
20
+ # The broker answered with a status that is not 2xx. The message is the
21
+ # broker's own sentence.
22
+ class APIError < Error
23
+ attr_reader :status, :body
24
+
25
+ def self.for(status, body)
26
+ klass = case status
27
+ when 401 then AuthenticationError
28
+ when 403 then PermissionError
29
+ when 404 then NotFoundError
30
+ when 422 then InvalidRequestError
31
+ when 502 then GatewayError
32
+ else APIError
33
+ end
34
+
35
+ klass.new(message_from(status, body), status: status, body: body)
36
+ end
37
+
38
+ def self.message_from(status, body)
39
+ error = body['error'] if body.is_a?(Hash)
40
+ errors = body['errors'] if body.is_a?(Hash)
41
+
42
+ return error if error.is_a?(String)
43
+ return errors.map { |field, message| "#{field}: #{message}" }.join('; ') if errors.is_a?(Hash)
44
+ return errors.join('; ') if errors.is_a?(Array)
45
+
46
+ "HTTP #{status}"
47
+ end
48
+
49
+ def initialize(message, status:, body:)
50
+ super(message)
51
+
52
+ @status = status
53
+ @body = body
54
+ end
55
+
56
+ # @return [Hash] one message per field, or {} when the broker sent none
57
+ def errors = (body.is_a?(Hash) && body['errors'].is_a?(Hash)) ? body['errors'] : {}
58
+ end
59
+
60
+ # 401: the secret key is missing or wrong.
61
+ class AuthenticationError < APIError; end
62
+
63
+ # 403: the app is paused or the key cannot do this.
64
+ class PermissionError < APIError; end
65
+
66
+ # 404: no session or subscription with that id for this app.
67
+ class NotFoundError < APIError; end
68
+
69
+ # 422: a field is invalid; {APIError#errors} says which.
70
+ class InvalidRequestError < APIError; end
71
+
72
+ # 502: the gateway refused or failed.
73
+ class GatewayError < APIError; end
74
+ end
75
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ContaGorda
4
+ module Pay
5
+ # A verified webhook event.
6
+ #
7
+ # event.id # the same on every retry of this delivery: dedupe on it
8
+ # event.type # "subscription.activated", "session.paid", …
9
+ # event.subscription # data.subscription, for subscription.* events
10
+ # event.session # data.session, for session.* events
11
+ # event.customer_ref # the customer[external_ref] the app sent to connect
12
+ # event.metadata # the metadata the app sent to connect
13
+ #
14
+ # The events: session.paid, session.failed, session.expired,
15
+ # session.refunded, subscription.activated, subscription.renewed,
16
+ # subscription.past_due, subscription.canceling, subscription.resumed,
17
+ # subscription.canceled, and ping (the dashboard's test).
18
+ class Event < Resource
19
+ def data = self[:data] || Resource.new
20
+
21
+ def subscription = data[:subscription]
22
+
23
+ def session = data[:session]
24
+
25
+ # @return [Resource, nil] the subscription or the session the event is about
26
+ def object = subscription || session
27
+
28
+ def customer_ref = object&.dig(:customer, :external_ref)
29
+
30
+ def metadata = object&.[](:metadata) || Resource.new
31
+
32
+ def livemode? = self[:livemode] == true
33
+
34
+ def created_at = self[:created_at] && Time.iso8601(self[:created_at])
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ContaGorda
4
+ module Pay
5
+ # A JSON object from the broker. Read a field as a method or by key, with a
6
+ # string or a symbol:
7
+ #
8
+ # subscription.status # => "active"
9
+ # subscription[:customer][:email]
10
+ # subscription.dig('metadata', 'plan')
11
+ #
12
+ # A field named like a Ruby method (a session's +method+) is read by key:
13
+ # +session[:method]+.
14
+ class Resource
15
+ def self.wrap(value)
16
+ case value
17
+ when Hash then Resource.new(value)
18
+ when Array then value.map { |item| wrap(item) }
19
+ else value
20
+ end
21
+ end
22
+
23
+ def initialize(attributes = {})
24
+ @attributes = attributes.to_h { |key, value| [key.to_sym, Resource.wrap(value)] }
25
+ end
26
+
27
+ def [](key) = @attributes[key.to_sym]
28
+
29
+ def key?(key) = @attributes.key?(key.to_sym)
30
+
31
+ def dig(key, *rest)
32
+ value = self[key]
33
+
34
+ (rest.empty? || value.nil?) ? value : value.dig(*rest)
35
+ end
36
+
37
+ def to_h = @attributes.transform_values { |value| unwrap(value) }
38
+
39
+ def deconstruct_keys(keys) = keys ? to_h.slice(*keys) : to_h
40
+
41
+ def ==(other) = other.is_a?(Resource) && other.to_h == to_h
42
+
43
+ def method_missing(name, *args)
44
+ return @attributes[name] if args.empty? && @attributes.key?(name)
45
+
46
+ super
47
+ end
48
+
49
+ def respond_to_missing?(name, include_private = false) = @attributes.key?(name) || super
50
+
51
+ def inspect
52
+ id = @attributes[:id]
53
+
54
+ "#<#{self.class.name}#{" id=#{id}" if id} #{@attributes.keys.join(', ')}>"
55
+ end
56
+
57
+ private
58
+
59
+ def unwrap(value)
60
+ case value
61
+ when Resource then value.to_h
62
+ when Array then value.map { |item| unwrap(item) }
63
+ else value
64
+ end
65
+ end
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ContaGorda
4
+ module Pay
5
+ # The signed proof the broker appends to +return_to+ when the customer
6
+ # comes back from the checkout: +?session_id=…&pay_token=…+. It is a JWS
7
+ # (HS256) signed with the app's secret key, issued by "pay", about that
8
+ # session, and it expires in minutes.
9
+ #
10
+ # It says what to SHOW ("payment received"). Do not grant anything from it:
11
+ # the customer's browser carries it and can replay it until it expires.
12
+ # Change the plan, or release the order, on the webhook.
13
+ #
14
+ # @example
15
+ # claims = ContaGorda::Pay::ReturnToken.new.verify(params[:pay_token], session_id: params[:session_id])
16
+ # claims&.status # => "paid", or nil when the token does not verify
17
+ class ReturnToken
18
+ ISSUER = 'pay'
19
+ ALGORITHM = 'HS256'
20
+
21
+ def initialize(secret_key: nil, leeway: 30)
22
+ @secret_key = secret_key || Pay.configuration.secret_key
23
+ @leeway = leeway
24
+
25
+ raise ConfigurationError, 'no secret key: pass secret_key: or set PAY_SECRET_KEY' if @secret_key.to_s.empty?
26
+ end
27
+
28
+ # @return [Resource, nil] the claims (status, amount, currency, customer,
29
+ # subscription…), or nil when the token is missing, forged, expired or
30
+ # about another session
31
+ def verify(token, session_id:, now: Time.now)
32
+ parts = token.to_s.split('.', -1)
33
+
34
+ return nil unless parts.length == 3 && !session_id.to_s.empty?
35
+
36
+ header64, payload64, signature64 = parts
37
+
38
+ header = JSON.parse(decode(header64))
39
+
40
+ return nil unless header.is_a?(Hash) && header['alg'] == ALGORITHM
41
+
42
+ expected = OpenSSL::HMAC.digest('SHA256', @secret_key, "#{header64}.#{payload64}")
43
+
44
+ return nil unless OpenSSL.secure_compare(expected, decode(signature64))
45
+
46
+ claims = JSON.parse(decode(payload64))
47
+
48
+ return nil unless valid?(claims, session_id.to_s, now.to_i)
49
+
50
+ Resource.new(claims)
51
+ rescue JSON::ParserError, ArgumentError
52
+ nil
53
+ end
54
+
55
+ def inspect = "#<#{self.class.name}>"
56
+
57
+ private
58
+
59
+ def valid?(claims, session_id, now)
60
+ claims.is_a?(Hash) &&
61
+ claims['iss'] == ISSUER &&
62
+ claims['sub'] == session_id &&
63
+ claims['exp'].is_a?(Integer) &&
64
+ now <= claims['exp'] + @leeway
65
+ end
66
+
67
+ def decode(part) = "#{part.tr('-_', '+/')}#{'=' * (-part.length % 4)}".unpack1('m0')
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../pay'
4
+
5
+ module ContaGorda
6
+ module Pay
7
+ # Builds what the broker sends, signed, for the app's own tests. Load it
8
+ # in the test helper only: +require 'contagorda/pay/testing'+.
9
+ #
10
+ # @example A Rails request test
11
+ # body = ContaGorda::Pay::Testing.payload('subscription.activated', subscription: {id: 'sub_1'})
12
+ #
13
+ # post '/webhooks/pay', params: body, headers: ContaGorda::Pay::Testing.headers(body)
14
+ module Testing
15
+ module_function
16
+
17
+ # @return [String] the JSON body of an event
18
+ def payload(type, data = {}, id: SecureRandom.uuid, livemode: false, created_at: Time.now)
19
+ JSON.generate(id: id, type: type, created_at: created_at.utc.iso8601, livemode: livemode, data: data)
20
+ end
21
+
22
+ # @return [String] the X-Pay-Signature header for this body
23
+ def signature(payload, secret: nil, at: Time.now)
24
+ secret ||= Pay.configuration.webhook_secret
25
+ timestamp = at.to_i
26
+
27
+ raise ConfigurationError, 'no webhook secret: pass secret: or set PAY_WEBHOOK_SECRET' if secret.to_s.empty?
28
+
29
+ "t=#{timestamp},v1=#{OpenSSL::HMAC.hexdigest('SHA256', secret, "#{timestamp}.#{payload}")}"
30
+ end
31
+
32
+ # @return [Hash] the headers of a delivery of this body
33
+ def headers(payload, secret: nil, at: Time.now)
34
+ {
35
+ 'Content-Type' => 'application/json',
36
+ 'X-Pay-Event-Id' => JSON.parse(payload)['id'].to_s,
37
+ 'X-Pay-Signature' => signature(payload, secret: secret, at: at)
38
+ }
39
+ end
40
+
41
+ # @return [String] a pay_token, as the broker appends to return_to
42
+ def return_token(session_id:, status: 'paid', secret_key: nil, expires_in: 900, now: Time.now, **claims)
43
+ secret_key ||= Pay.configuration.secret_key
44
+
45
+ raise ConfigurationError, 'no secret key: pass secret_key: or set PAY_SECRET_KEY' if secret_key.to_s.empty?
46
+
47
+ body = {iss: ReturnToken::ISSUER, sub: session_id, status: status, iat: now.to_i, exp: now.to_i + expires_in}.merge(claims)
48
+ signing_input = "#{encode(JSON.generate(alg: ReturnToken::ALGORITHM, typ: 'JWT'))}.#{encode(JSON.generate(body))}"
49
+
50
+ "#{signing_input}.#{encode(OpenSSL::HMAC.digest('SHA256', secret_key, signing_input))}"
51
+ end
52
+
53
+ def encode(bytes) = [bytes].pack('m0').tr('+/', '-_').delete('=')
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ContaGorda
4
+ module Pay
5
+ VERSION = '0.1.0'
6
+ end
7
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ContaGorda
4
+ module Pay
5
+ class Webhook
6
+ # A Rack endpoint for the broker's webhooks. It verifies the signature,
7
+ # builds the {Event} and calls the handler with it. It needs no `rack`
8
+ # gem and works in Rails, Sinatra, Hanami or a plain config.ru.
9
+ #
10
+ # bad signature 401, the broker retries
11
+ # body is not an event 400
12
+ # handler returns 200, the broker stops
13
+ # handler raises the error goes up (500), the broker retries
14
+ #
15
+ # Storing the event is the app's job. The broker retries, so the handler
16
+ # can see the same event.id more than once: make it idempotent, or save
17
+ # event.id with a unique index first and stop when it is already there.
18
+ #
19
+ # @example Rails, config/routes.rb
20
+ # post '/webhooks/pay', to: ContaGorda::Pay::Webhook::Endpoint.new { |event| Billing.receive(event) }
21
+ #
22
+ # @example Sinatra or config.ru
23
+ # map('/webhooks/pay') { run ContaGorda::Pay::Webhook::Endpoint.new(BillingHandler) }
24
+ class Endpoint
25
+ # @param handler [#call] receives the {Event}; or pass a block
26
+ # @param secret [String, nil] the signing secret, PAY_WEBHOOK_SECRET by default
27
+ def initialize(handler = nil, secret: nil, tolerance: Webhook::TOLERANCE, &block)
28
+ @handler = handler || block
29
+ @secret = secret
30
+ @tolerance = tolerance
31
+
32
+ raise ConfigurationError, 'pass a handler that responds to call, or a block' unless @handler.respond_to?(:call)
33
+ end
34
+
35
+ def call(env)
36
+ return reply(405, 'allow' => 'POST') unless env['REQUEST_METHOD'] == 'POST'
37
+
38
+ event = Webhook.new(secret: @secret, tolerance: @tolerance).event(read(env['rack.input']), env['HTTP_X_PAY_SIGNATURE'])
39
+
40
+ @handler.call(event)
41
+
42
+ reply(200)
43
+ rescue SignatureError
44
+ reply(401)
45
+ rescue InvalidPayloadError
46
+ reply(400)
47
+ end
48
+
49
+ def inspect = "#<#{self.class.name}>"
50
+
51
+ private
52
+
53
+ def read(input)
54
+ return '' unless input
55
+
56
+ input.rewind if input.respond_to?(:rewind)
57
+
58
+ body = input.read.to_s
59
+
60
+ input.rewind if input.respond_to?(:rewind)
61
+
62
+ body
63
+ end
64
+
65
+ def reply(status, headers = {}) = [status, {'content-type' => 'text/plain'}.merge(headers), []]
66
+ end
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ContaGorda
4
+ module Pay
5
+ # Verifies a webhook delivery and answers the {Event}.
6
+ #
7
+ # X-Pay-Signature: t=<unix time>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>
8
+ #
9
+ # Pass the RAW body (+request.raw_post+, +request.body.read+). Parsing the
10
+ # JSON and serializing it again changes the bytes and the signature fails.
11
+ #
12
+ # @example In a Rails controller
13
+ # event = ContaGorda::Pay::Webhook.new.event(request.raw_post, request.headers['X-Pay-Signature'])
14
+ #
15
+ # For a ready endpoint, see {Webhook::Endpoint}.
16
+ class Webhook
17
+ SIGNATURE_HEADER = 'X-Pay-Signature'
18
+
19
+ # Seconds a signature stays valid, against replays of an old delivery.
20
+ TOLERANCE = 300
21
+
22
+ def initialize(secret: nil, tolerance: TOLERANCE)
23
+ @secret = secret || Pay.configuration.webhook_secret
24
+ @tolerance = tolerance
25
+
26
+ raise ConfigurationError, 'no webhook secret: pass secret: or set PAY_WEBHOOK_SECRET' if @secret.to_s.empty?
27
+ end
28
+
29
+ # @param payload [String] the raw request body
30
+ # @param signature [String, nil] the X-Pay-Signature header
31
+ # @return [Event]
32
+ # @raise [SignatureError] when the signature does not verify
33
+ # @raise [InvalidPayloadError] when the body is not an event
34
+ def event(payload, signature, now: Time.now)
35
+ raise InvalidPayloadError, 'pass the raw body as a String, not parsed params' unless payload.is_a?(String)
36
+
37
+ verify!(payload, signature.to_s, now)
38
+
39
+ data = JSON.parse(payload)
40
+
41
+ raise InvalidPayloadError, 'the event has no id or no type' unless event?(data)
42
+
43
+ Event.new(data)
44
+ rescue JSON::ParserError
45
+ raise InvalidPayloadError, 'the body is not JSON'
46
+ end
47
+
48
+ def inspect = "#<#{self.class.name}>"
49
+
50
+ private
51
+
52
+ def verify!(payload, header, now)
53
+ pairs = header.split(',').map { |part| part.strip.split('=', 2) }
54
+ timestamp = pairs.find { |key, _| key == 't' }&.last
55
+ signatures = pairs.filter_map { |key, value| value if key == 'v1' }
56
+
57
+ raise SignatureError, "#{SIGNATURE_HEADER} is missing or malformed" unless timestamp&.match?(/\A\d+\z/) && signatures.any?
58
+ raise SignatureError, "#{SIGNATURE_HEADER} is older than #{@tolerance}s" if (now.to_i - timestamp.to_i).abs > @tolerance
59
+
60
+ expected = OpenSSL::HMAC.hexdigest('SHA256', @secret, "#{timestamp}.#{payload}")
61
+
62
+ raise SignatureError, "#{SIGNATURE_HEADER} does not match the body" unless signatures.any? { |given| OpenSSL.secure_compare(expected, given) }
63
+ end
64
+
65
+ def event?(data) = data.is_a?(Hash) && present?(data['id']) && present?(data['type'])
66
+
67
+ def present?(value) = value.is_a?(String) && !value.empty?
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'net/http'
5
+ require 'openssl'
6
+ require 'securerandom'
7
+ require 'time'
8
+ require 'uri'
9
+
10
+ require_relative 'pay/version'
11
+ require_relative 'pay/errors'
12
+ require_relative 'pay/configuration'
13
+ require_relative 'pay/resource'
14
+ require_relative 'pay/event'
15
+ require_relative 'pay/client'
16
+ require_relative 'pay/webhook'
17
+ require_relative 'pay/webhook/endpoint'
18
+ require_relative 'pay/return_token'
19
+
20
+ module ContaGorda
21
+ # Ruby SDK for the Pay broker: start a checkout, read and change
22
+ # subscriptions, verify the signed return and receive the signed webhooks.
23
+ #
24
+ # Billing stays in the app. The gem only formalizes the payment: the app does
25
+ # not know which gateway takes the money, it sends one request and hears
26
+ # back by webhook.
27
+ module Pay
28
+ class << self
29
+ # @return [Configuration] defaults read by {Client}, {Webhook} and {ReturnToken}
30
+ def configuration = @configuration ||= Configuration.new
31
+
32
+ # Stores defaults; nothing reaches the network.
33
+ #
34
+ # @example
35
+ # ContaGorda::Pay.configure do |config|
36
+ # config.secret_key = ENV['PAY_SECRET_KEY']
37
+ # end
38
+ def configure
39
+ yield configuration
40
+
41
+ configuration
42
+ end
43
+
44
+ # @return [Boolean] true when a secret key is set, so a checkout can be opened
45
+ def configured? = !configuration.secret_key.nil?
46
+
47
+ def reset! = @configuration = Configuration.new
48
+ end
49
+ end
50
+ end
metadata ADDED
@@ -0,0 +1,149 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: contagorda-pay
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Thadeu Esteves Jr
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rack
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '2.2'
19
+ type: :development
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '2.2'
26
+ - !ruby/object:Gem::Dependency
27
+ name: rake
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '13.0'
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '13.0'
40
+ - !ruby/object:Gem::Dependency
41
+ name: rspec
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '3.13'
47
+ - - "<"
48
+ - !ruby/object:Gem::Version
49
+ version: '4.0'
50
+ type: :development
51
+ prerelease: false
52
+ version_requirements: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: '3.13'
57
+ - - "<"
58
+ - !ruby/object:Gem::Version
59
+ version: '4.0'
60
+ - !ruby/object:Gem::Dependency
61
+ name: simplecov
62
+ requirement: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: '0.22'
67
+ type: :development
68
+ prerelease: false
69
+ version_requirements: !ruby/object:Gem::Requirement
70
+ requirements:
71
+ - - ">="
72
+ - !ruby/object:Gem::Version
73
+ version: '0.22'
74
+ - !ruby/object:Gem::Dependency
75
+ name: standard
76
+ requirement: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ version: '1.0'
81
+ type: :development
82
+ prerelease: false
83
+ version_requirements: !ruby/object:Gem::Requirement
84
+ requirements:
85
+ - - ">="
86
+ - !ruby/object:Gem::Version
87
+ version: '1.0'
88
+ - !ruby/object:Gem::Dependency
89
+ name: webmock
90
+ requirement: !ruby/object:Gem::Requirement
91
+ requirements:
92
+ - - ">="
93
+ - !ruby/object:Gem::Version
94
+ version: '3.23'
95
+ type: :development
96
+ prerelease: false
97
+ version_requirements: !ruby/object:Gem::Requirement
98
+ requirements:
99
+ - - ">="
100
+ - !ruby/object:Gem::Version
101
+ version: '3.23'
102
+ description: 'Open a checkout, read and cancel subscriptions, verify the signed return
103
+ and receive signed webhooks from the Pay broker. Standard library only: no runtime
104
+ dependencies. Ruby 3.0 and up. Works in Rails, Sinatra, Hanami or plain Rack.'
105
+ executables: []
106
+ extensions: []
107
+ extra_rdoc_files: []
108
+ files:
109
+ - CHANGELOG.md
110
+ - LICENSE
111
+ - README.md
112
+ - contagorda-pay.gemspec
113
+ - lib/contagorda/pay.rb
114
+ - lib/contagorda/pay/client.rb
115
+ - lib/contagorda/pay/configuration.rb
116
+ - lib/contagorda/pay/errors.rb
117
+ - lib/contagorda/pay/event.rb
118
+ - lib/contagorda/pay/resource.rb
119
+ - lib/contagorda/pay/return_token.rb
120
+ - lib/contagorda/pay/testing.rb
121
+ - lib/contagorda/pay/version.rb
122
+ - lib/contagorda/pay/webhook.rb
123
+ - lib/contagorda/pay/webhook/endpoint.rb
124
+ homepage: https://pay.contagorda.com/docs
125
+ licenses:
126
+ - MIT
127
+ metadata:
128
+ rubygems_mfa_required: 'true'
129
+ documentation_uri: https://pay.contagorda.com/docs
130
+ source_code_uri: https://github.com/thadeu/contagorda-pay/tree/main/gems/contagorda-pay
131
+ changelog_uri: https://github.com/thadeu/contagorda-pay/blob/main/gems/contagorda-pay/CHANGELOG.md
132
+ rdoc_options: []
133
+ require_paths:
134
+ - lib
135
+ required_ruby_version: !ruby/object:Gem::Requirement
136
+ requirements:
137
+ - - ">="
138
+ - !ruby/object:Gem::Version
139
+ version: '3.0'
140
+ required_rubygems_version: !ruby/object:Gem::Requirement
141
+ requirements:
142
+ - - ">="
143
+ - !ruby/object:Gem::Version
144
+ version: '0'
145
+ requirements: []
146
+ rubygems_version: 4.0.20
147
+ specification_version: 4
148
+ summary: Ruby SDK for the ContaGorda Pay broker
149
+ test_files: []