sumup 0.0.1

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.
Files changed (44) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +18 -0
  3. data/LICENSE +201 -0
  4. data/README.md +188 -0
  5. data/lib/sumup/client.rb +213 -0
  6. data/lib/sumup/errors.rb +45 -0
  7. data/lib/sumup/event_types.rb +115 -0
  8. data/lib/sumup/events.rb +168 -0
  9. data/lib/sumup/model.rb +109 -0
  10. data/lib/sumup/pagination.rb +92 -0
  11. data/lib/sumup/resource.rb +36 -0
  12. data/lib/sumup/resources/checkouts.rb +155 -0
  13. data/lib/sumup/resources/customers.rb +89 -0
  14. data/lib/sumup/resources/members.rb +93 -0
  15. data/lib/sumup/resources/memberships.rb +23 -0
  16. data/lib/sumup/resources/merchants.rb +51 -0
  17. data/lib/sumup/resources/payouts.rb +29 -0
  18. data/lib/sumup/resources/readers.rb +264 -0
  19. data/lib/sumup/resources/receipts.rb +23 -0
  20. data/lib/sumup/resources/roles.rb +89 -0
  21. data/lib/sumup/resources/sales.rb +66 -0
  22. data/lib/sumup/resources/tokens.rb +31 -0
  23. data/lib/sumup/resources/transactions.rb +61 -0
  24. data/lib/sumup/resources.rb +83 -0
  25. data/lib/sumup/transport.rb +40 -0
  26. data/lib/sumup/types.rb +4720 -0
  27. data/lib/sumup/version.rb +5 -0
  28. data/lib/sumup.rb +13 -0
  29. data/sig/sumup/events.rbs +64 -0
  30. data/sig/sumup/resources/checkouts.rbs +35 -0
  31. data/sig/sumup/resources/customers.rbs +25 -0
  32. data/sig/sumup/resources/members.rbs +25 -0
  33. data/sig/sumup/resources/memberships.rbs +13 -0
  34. data/sig/sumup/resources/merchants.rbs +17 -0
  35. data/sig/sumup/resources/payouts.rbs +13 -0
  36. data/sig/sumup/resources/readers.rbs +45 -0
  37. data/sig/sumup/resources/receipts.rbs +13 -0
  38. data/sig/sumup/resources/roles.rbs +25 -0
  39. data/sig/sumup/resources/sales.rbs +19 -0
  40. data/sig/sumup/resources/tokens.rbs +15 -0
  41. data/sig/sumup/resources/transactions.rbs +19 -0
  42. data/sig/sumup/types.rbs +1635 -0
  43. data/sig/sumup.rbs +183 -0
  44. metadata +149 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0aa477c414d21a49b4381a25f0af2f54adbd8b11523d031d9a8b210e52c1be16
4
+ data.tar.gz: d40bc7b5813c6e8be5c26670cd602f6f90c38e91b94d196eced1c08d833e8dc7
5
+ SHA512:
6
+ metadata.gz: 68f74aea1610c3e658f43c29d0e34af904a9c5751853e9c5c4bffdcce75ffa623599c670271639ab37d6df96a8079fdd8def00592bd89829f5773f9bbf4c99bb
7
+ data.tar.gz: f80a039038ec422134b341f7da4beca141cd9489c5366b3538e1326019b0e700940241ee62923d0630acf034b3fd659a72346e537630a3d5c6c56aca55ac0b8a
data/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ ## 0.0.1 (2026-11-16)
4
+
5
+
6
+ ### Features
7
+
8
+ * init ([611031a](https://github.com/sumup/sumup-ruby/commit/611031ae5fcc2aaedfaf391e3707d3f0987b0728))
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * release please config ([53804a1](https://github.com/sumup/sumup-ruby/commit/53804a19e4f35b5afabd1c00f12979d37acc0fea))
14
+
15
+ ## 0.0.1
16
+
17
+ - Initial Ruby SDK covering the public SumUp API, generated models and RBS
18
+ signatures, signed events, pagination, and configurable HTTP transport.
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2019 SumUp Ltd
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,188 @@
1
+ <div align="center">
2
+
3
+ # SumUp Ruby SDK
4
+
5
+ [![CI](https://github.com/sumup/sumup-ruby/actions/workflows/ci.yaml/badge.svg)](https://github.com/sumup/sumup-ruby/actions/workflows/ci.yaml)
6
+ [![Ruby](https://img.shields.io/badge/Ruby-3.3%2B-ruby?logo=ruby)](sumup.gemspec)
7
+ [![Documentation](https://img.shields.io/badge/SumUp-documentation-white)](https://developer.sumup.com)
8
+ [![License](https://img.shields.io/github/license/sumup/sumup-ruby)](LICENSE)
9
+
10
+ </div>
11
+
12
+ Use the SumUp Ruby SDK to create checkouts, manage card readers, and access the
13
+ [SumUp API](https://developer.sumup.com/api/). Requires Ruby 3.3 or later.
14
+
15
+ ## Installation
16
+
17
+ The SDK has not been published yet. Add your local checkout to your application's
18
+ Gemfile:
19
+
20
+ ```ruby
21
+ gem "sumup", path: "../sumup-ruby"
22
+ ```
23
+
24
+ Then run `bundle install`.
25
+
26
+ ## Usage
27
+
28
+ Create a [sandbox merchant](https://developer.sumup.com/online-payments/testing/)
29
+ and an [API key](https://developer.sumup.com/tools/authorization/api-keys/).
30
+ Set `SUMUP_API_KEY` and `SUMUP_MERCHANT_CODE` in your environment.
31
+
32
+ ### Create a checkout
33
+
34
+ ```ruby
35
+ require "sumup"
36
+ require "securerandom"
37
+
38
+ client = SumUp::Client.new(api_key: ENV.fetch("SUMUP_API_KEY"))
39
+
40
+ checkout = client.checkouts.create(
41
+ checkout_reference: SecureRandom.uuid,
42
+ amount: 19.99,
43
+ currency: "EUR",
44
+ merchant_code: ENV.fetch("SUMUP_MERCHANT_CODE"),
45
+ description: "Order 1234",
46
+ hosted_checkout: {enabled: true}
47
+ )
48
+
49
+ puts checkout.id
50
+ puts checkout.hosted_checkout_url
51
+ ```
52
+
53
+ Send the customer to `hosted_checkout_url` to pay. Retrieve the checkout on your
54
+ server to verify its status before fulfilling the order. Keep credentials on your
55
+ server. Sandbox merchants use the same API URL as live merchants.
56
+
57
+ Request bodies accept keyword arguments, a Hash, or a model from `SumUp::Types`.
58
+ Response fields are available as Ruby methods or through `object["field_name"]`;
59
+ `to_h` preserves unknown fields and explicit nulls. RBS signatures are included.
60
+
61
+ ### Accept a payment on a reader
62
+
63
+ Use a paired reader and the credentials required by the
64
+ [Cloud API](https://developer.sumup.com/terminal-payments/cloud-api/):
65
+
66
+ ```ruby
67
+ result = client.readers.create_checkout(
68
+ merchant_code: ENV.fetch("SUMUP_MERCHANT_CODE"),
69
+ reader_id: ENV.fetch("SUMUP_READER_ID"),
70
+ total_amount: {currency: "EUR", minor_unit: 2, value: 1999},
71
+ description: "Order 1234"
72
+ )
73
+
74
+ puts result.data.client_transaction_id
75
+ ```
76
+
77
+ Online checkout amounts use major units (`19.99` EUR); reader amounts use minor
78
+ units (`1999` cents). Starting a reader checkout does not confirm payment. Follow
79
+ its status notifications and verify the transaction through the API.
80
+
81
+ ### Handle errors
82
+
83
+ ```ruby
84
+ begin
85
+ checkout = client.checkouts.get(checkout_id: "CHECKOUT_ID")
86
+ rescue SumUp::RateLimitError => error
87
+ warn "Rate limited (HTTP #{error.status})"
88
+ rescue SumUp::APIError => error
89
+ warn "API request failed (HTTP #{error.status}, request #{error.request_id})"
90
+ rescue SumUp::APIConnectionError => error
91
+ warn "Connection failed: #{error.class}"
92
+ end
93
+ ```
94
+
95
+ API errors expose `status`, `request_id`, and `body`, plus a typed `problem` when
96
+ returned by the API. Treat error bodies as sensitive data.
97
+
98
+ Every operation also has a `_with_response` variant for response metadata:
99
+
100
+ ```ruby
101
+ response = client.checkouts.get_with_response(checkout_id: "CHECKOUT_ID")
102
+ puts response.status
103
+ puts response.request_id
104
+ checkout = response.data
105
+ ```
106
+
107
+ ### Paginate results
108
+
109
+ Use lazy enumerators for sales, sales search, transaction history, members, and
110
+ memberships. Pages are fetched as needed:
111
+
112
+ ```ruby
113
+ client.transactions.each(
114
+ merchant_code: ENV.fetch("SUMUP_MERCHANT_CODE"),
115
+ statuses: ["SUCCESSFUL"]
116
+ ).take(10).each { |transaction| puts transaction.transaction_code }
117
+ ```
118
+
119
+ ### Configure requests
120
+
121
+ Pass an OAuth access token through `api_key` to act on behalf of another merchant.
122
+ Your application owns authorization, token storage, and refresh; see the
123
+ [OAuth example](examples/oauth2/).
124
+
125
+ Override credentials, timeouts, or headers for an individual request:
126
+
127
+ ```ruby
128
+ checkout = client.checkouts.get(
129
+ checkout_id: "CHECKOUT_ID",
130
+ options: {
131
+ api_key: merchant_access_token,
132
+ timeout: 15,
133
+ headers: {"X-Correlation-ID" => "order-1234"}
134
+ }
135
+ )
136
+ ```
137
+
138
+ Defaults are a 10-second connection timeout, 60-second read/write timeouts, and
139
+ **zero automatic retries**. Set `max_retries` on the client or request to enable
140
+ retries for transient failures. Retries also apply to writes; enable them only
141
+ when the operation is safe to repeat.
142
+
143
+ ### Handle signed events
144
+
145
+ Pass the unchanged request body and complete `X-SumUp-Webhook-Signature` header
146
+ to the handler:
147
+
148
+ ```ruby
149
+ handler = client.events_handler(
150
+ secret: ENV.fetch("SUMUP_WEBHOOK_SECRET"),
151
+ fallback: ->(event) { warn "Unhandled event: #{event.type}" }
152
+ )
153
+
154
+ handler.on(SumUp::CheckoutPaidEvent::TYPE) do |event|
155
+ checkout = event.fetch_object
156
+ # Deduplicate by event.id and verify the checkout before fulfillment.
157
+ end
158
+
159
+ handler.handle(raw_request_body, signature: signature_header)
160
+ ```
161
+
162
+ The handler verifies the signature before calling your callbacks. `fetch_object`
163
+ retrieves the resource's current state. Return 2xx after processing succeeds, 400
164
+ for invalid signatures or payloads, and 5xx for callback failures so delivery can
165
+ be retried. Callbacks must tolerate repeated and out-of-order deliveries.
166
+
167
+ Signed events are separate from legacy checkout `return_url` callbacks. See the
168
+ [Rack event receiver](examples/events/) for a complete route and the
169
+ [checkout webhook guide](https://developer.sumup.com/online-payments/webhooks/)
170
+ for legacy callbacks.
171
+
172
+ ## Examples and documentation
173
+
174
+ - [Create a checkout](examples/checkout.rb)
175
+ - [Create a reader checkout](examples/card_reader_checkout.rb)
176
+ - [Connect a merchant with OAuth](examples/oauth2/)
177
+ - [Receive signed events](examples/events/)
178
+ - [API reference](https://developer.sumup.com/api/)
179
+ - [Contributing](CONTRIBUTING.md)
180
+
181
+ ## Support
182
+
183
+ For bugs and feature requests, [open an issue](https://github.com/sumup/sumup-ruby/issues).
184
+ For integration help, contact [integration@sumup.com](mailto:integration@sumup.com).
185
+
186
+ ## License
187
+
188
+ Licensed under [Apache 2.0](LICENSE).
@@ -0,0 +1,213 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+ require "json"
5
+ require "time"
6
+
7
+ module SumUp
8
+ UNSET = Object.new.freeze
9
+
10
+ # Per-call overrides. No configuration is changed on the shared Client.
11
+ class RequestOptions
12
+ attr_reader :headers, :api_key, :timeout, :open_timeout, :max_retries
13
+
14
+ def initialize(headers: {}, api_key: nil, timeout: nil, open_timeout: nil, max_retries: nil)
15
+ @headers = headers.to_h { |key, value| [key.to_s, value.to_s.dup.freeze] }.freeze
16
+ @api_key = api_key&.dup&.freeze
17
+ @timeout = timeout
18
+ @open_timeout = open_timeout
19
+ @max_retries = max_retries
20
+ end
21
+
22
+ def inspect
23
+ "#<SumUp::RequestOptions>"
24
+ end
25
+ end
26
+
27
+ # Decoded data plus status, headers, raw body, and request identifier.
28
+ Response = Data.define(:data, :status, :headers, :body) do
29
+ def request_id
30
+ headers["x-request-id"] || headers["x-correlation-id"]
31
+ end
32
+
33
+ def inspect
34
+ "#<SumUp::Response status=#{status}>"
35
+ end
36
+ alias_method :to_s, :inspect
37
+ end
38
+
39
+ class Client
40
+ DEFAULT_BASE_URL = "https://api.sumup.com"
41
+ RETRY_STATUSES = [408, 409, 429, 500, 502, 503, 504].freeze
42
+
43
+ attr_reader :base_url
44
+
45
+ # api_key accepts either an API key or an OAuth access token.
46
+ # Retries default to zero, as they do in the other SumUp SDKs. Enabling
47
+ # retries also retries writes: only opt in when the operation is safe to repeat.
48
+ def initialize(api_key: nil, base_url: DEFAULT_BASE_URL, timeout: 60, open_timeout: 10,
49
+ max_retries: 0, transport: NetHTTPTransport.new, headers: {}, sleeper: Kernel.method(:sleep))
50
+ @base_url = base_url.to_s.delete_suffix("/").freeze
51
+ uri = URI.parse(@base_url)
52
+ unless %w[http https].include?(uri.scheme) && uri.host && !uri.userinfo && !uri.query && !uri.fragment
53
+ raise ArgumentError, "base_url must be an HTTP(S) URL without credentials, query, or fragment"
54
+ end
55
+ @api_key = api_key&.dup&.freeze
56
+ @timeout = positive(timeout, "timeout")
57
+ @open_timeout = positive(open_timeout, "open_timeout")
58
+ @max_retries = retries(max_retries)
59
+ @transport = transport
60
+ @headers = normalize_headers(headers).freeze
61
+ @sleeper = sleeper
62
+ @resources = self.class::RESOURCES.to_h { |name, klass| [name, klass.new(self)] }.freeze
63
+ rescue URI::InvalidURIError
64
+ raise ArgumentError, "invalid base_url"
65
+ end
66
+
67
+ def inspect
68
+ "#<SumUp::Client>"
69
+ end
70
+
71
+ # Low-level escape hatch for API operations not yet present in this release.
72
+ # Absolute URLs are accepted only for the client's configured API origin.
73
+ def request(method:, path:, query: {}, body: UNSET, options: nil, response_type: nil, with_response: false)
74
+ options = RequestOptions.new(**options) if options.is_a?(Hash)
75
+ options ||= RequestOptions.new
76
+ raise ArgumentError, "options must be RequestOptions or a Hash" unless options.is_a?(RequestOptions)
77
+ uri = request_uri(path, query)
78
+ headers = {
79
+ "accept" => "application/problem+json, application/json",
80
+ "content-type" => "application/json",
81
+ "user-agent" => "sumup-ruby/#{VERSION} Ruby/#{RUBY_VERSION}"
82
+ }
83
+ headers["authorization"] = "Bearer #{@api_key}" if @api_key
84
+ headers.merge!(@headers)
85
+ headers["authorization"] = "Bearer #{options.api_key}" if options.api_key
86
+ headers.merge!(normalize_headers(options.headers))
87
+ message = Request.new(method: method.to_s.upcase, uri: uri, headers: headers.freeze,
88
+ body: body.equal?(UNSET) ? nil : JSON.generate(Types.encode(body)),
89
+ open_timeout: positive(options.open_timeout || @open_timeout, "open_timeout"),
90
+ read_timeout: positive(options.timeout || @timeout, "timeout"),
91
+ write_timeout: positive(options.timeout || @timeout, "timeout"))
92
+ raw = perform(message, retries(options.max_retries || @max_retries))
93
+ response_headers = normalize_headers(raw.headers).freeze
94
+ response_type = response_type.fetch(raw.status) { [:union, response_type.values.uniq] } if response_type.is_a?(Hash)
95
+ decoded = decode_body(raw, response_headers, response_type)
96
+ unless (200...300).cover?(raw.status)
97
+ error_class = (raw.status >= 500) ? InternalServerError : STATUS_ERRORS.fetch(raw.status, APIStatusError)
98
+ raise error_class.new(status: raw.status, body: decoded, headers: response_headers)
99
+ end
100
+ data = Types.decode(decoded, response_type)
101
+ with_response ? Response.new(data: data, status: raw.status, headers: response_headers, body: raw.body) : data
102
+ end
103
+
104
+ def events_handler(secret:, fallback:, &block)
105
+ handler = EventsHandler.new(client: self, secret: secret, fallback: fallback)
106
+ block&.call(handler)
107
+ handler
108
+ end
109
+
110
+ def parse_event_notification_without_verification(body)
111
+ Events.parse_without_verification(body, client: self)
112
+ end
113
+
114
+ private
115
+
116
+ def positive(value, name)
117
+ raise ArgumentError, "#{name} must be a positive finite number" unless value.is_a?(Numeric) && value.finite? && value.positive?
118
+ value
119
+ end
120
+
121
+ def retries(value)
122
+ raise ArgumentError, "max_retries must be a non-negative integer" unless value.is_a?(Integer) && value >= 0
123
+ value
124
+ end
125
+
126
+ def normalize_headers(headers)
127
+ headers.to_h { |key, value| [key.to_s.downcase, value.to_s.dup.freeze] }
128
+ end
129
+
130
+ def request_uri(path, query)
131
+ candidate = URI.parse(path.to_s)
132
+ uri = if candidate.absolute?
133
+ origin = URI.parse(base_url)
134
+ unless [candidate.scheme, candidate.hostname&.downcase, candidate.port] == [origin.scheme, origin.hostname&.downcase, origin.port]
135
+ raise ArgumentError, "resource URL must use the configured API origin"
136
+ end
137
+ candidate
138
+ else
139
+ raise ArgumentError, "path must begin with a single slash" unless path.to_s.start_with?("/") && !path.to_s.start_with?("//")
140
+ URI.parse(base_url + path.to_s)
141
+ end
142
+ raise ArgumentError, "resource URL cannot contain credentials or a fragment" if uri.userinfo || uri.fragment
143
+ pairs = query.reject { |_, value| value.equal?(UNSET) }.flat_map do |key, value|
144
+ Array(value).map { |item| [key.to_s, query_value(item)] }
145
+ end
146
+ uri.query = [uri.query, URI.encode_www_form(pairs)].reject { |part| part.nil? || part.empty? }.join("&")
147
+ uri.query = nil if uri.query == ""
148
+ uri
149
+ rescue URI::InvalidURIError
150
+ raise ArgumentError, "invalid resource URL"
151
+ end
152
+
153
+ def query_value(value)
154
+ case value
155
+ when String, Numeric, true, false then value.to_s
156
+ when Time, Date, DateTime then value.iso8601
157
+ else raise ArgumentError, "query values must be strings, numbers, booleans, dates, or arrays of those values"
158
+ end
159
+ end
160
+
161
+ def perform(request, max_retries)
162
+ attempt = 0
163
+ loop do
164
+ begin
165
+ response = @transport.call(request)
166
+ return response unless attempt < max_retries && RETRY_STATUSES.include?(response.status)
167
+ delay = retry_delay(response.headers, attempt)
168
+ rescue Timeout::Error
169
+ raise APITimeoutError, "SumUp request timed out" if attempt >= max_retries
170
+ delay = retry_delay({}, attempt)
171
+ rescue IOError, SocketError, SystemCallError, OpenSSL::SSL::SSLError
172
+ raise APIConnectionError, "Could not connect to the SumUp API" if attempt >= max_retries
173
+ delay = retry_delay({}, attempt)
174
+ end
175
+ @sleeper.call(delay)
176
+ attempt += 1
177
+ end
178
+ end
179
+
180
+ def retry_delay(headers, attempt)
181
+ value = normalize_headers(headers)["retry-after"]
182
+ if value
183
+ delay = parse_retry_after(value)
184
+ return [delay, 60].min if delay&.finite? && delay >= 0
185
+ end
186
+ [0.5 * (2**[attempt, 7].min), 30].min * (0.75 + Random.rand * 0.25)
187
+ end
188
+
189
+ def parse_retry_after(value)
190
+ Float(value, exception: false) || Time.httpdate(value) - Time.now
191
+ rescue ArgumentError
192
+ nil
193
+ end
194
+
195
+ def decode_body(raw, headers, response_type)
196
+ return nil if [204, 205].include?(raw.status) || raw.body.nil? || raw.body.empty?
197
+ unless headers.fetch("content-type", "").downcase.include?("json")
198
+ if (200...300).cover?(raw.status) && response_type && !accepts_text?(response_type)
199
+ raise InvalidResponseError, "SumUp returned a non-JSON response"
200
+ end
201
+ return raw.body
202
+ end
203
+ JSON.parse(raw.body)
204
+ rescue JSON::ParserError
205
+ return raw.body unless (200...300).cover?(raw.status)
206
+ raise InvalidResponseError, "SumUp returned invalid JSON"
207
+ end
208
+
209
+ def accepts_text?(type)
210
+ type == :string || type == :any || (type.is_a?(Array) && type.first == :union && type.last.any? { |variant| accepts_text?(variant) })
211
+ end
212
+ end
213
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SumUp
4
+ class Error < StandardError; end
5
+
6
+ class APIConnectionError < Error; end
7
+
8
+ class APITimeoutError < APIConnectionError; end
9
+
10
+ class InvalidResponseError < Error; end
11
+
12
+ class APIError < Error
13
+ attr_reader :status, :body, :headers, :request_id, :problem
14
+
15
+ def initialize(status:, body:, headers: {})
16
+ @status = status
17
+ @body = body
18
+ @headers = headers.freeze
19
+ @request_id = headers["x-request-id"] || headers["x-correlation-id"]
20
+ @problem = Types::Problem.new(body) if body.is_a?(Hash) && body["type"].is_a?(String)
21
+ # Error payloads may contain sensitive data. Inspect #body explicitly when needed.
22
+ super("SumUp API returned HTTP #{status}#{" (request #{@request_id})" if @request_id}")
23
+ end
24
+
25
+ def inspect
26
+ "#<#{self.class} status=#{status}>"
27
+ end
28
+ end
29
+
30
+ class APIStatusError < APIError; end
31
+ class BadRequestError < APIStatusError; end
32
+ class AuthenticationError < APIStatusError; end
33
+ class PermissionDeniedError < APIStatusError; end
34
+ class NotFoundError < APIStatusError; end
35
+ class ConflictError < APIStatusError; end
36
+ class UnprocessableEntityError < APIStatusError; end
37
+ class RateLimitError < APIStatusError; end
38
+ class InternalServerError < APIStatusError; end
39
+
40
+ STATUS_ERRORS = {
41
+ 400 => BadRequestError, 401 => AuthenticationError,
42
+ 403 => PermissionDeniedError, 404 => NotFoundError,
43
+ 409 => ConflictError, 422 => UnprocessableEntityError, 429 => RateLimitError
44
+ }.freeze
45
+ end