paysafe-tz 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 +7 -0
- data/CHANGELOG.md +25 -0
- data/LICENSE +21 -0
- data/README.md +162 -0
- data/lib/paysafe/api_response.rb +54 -0
- data/lib/paysafe/client.rb +210 -0
- data/lib/paysafe/errors.rb +179 -0
- data/lib/paysafe/models.rb +164 -0
- data/lib/paysafe/page.rb +60 -0
- data/lib/paysafe/request_options.rb +47 -0
- data/lib/paysafe/resources/balance.rb +19 -0
- data/lib/paysafe/resources/base.rb +76 -0
- data/lib/paysafe/resources/control_numbers.rb +70 -0
- data/lib/paysafe/resources/customers.rb +19 -0
- data/lib/paysafe/resources/events.rb +23 -0
- data/lib/paysafe/resources/payment_links.rb +66 -0
- data/lib/paysafe/resources/payments.rb +54 -0
- data/lib/paysafe/resources/refunds.rb +39 -0
- data/lib/paysafe/resources/topups.rb +35 -0
- data/lib/paysafe/resources/transfers.rb +33 -0
- data/lib/paysafe/resources/webhook_endpoints.rb +55 -0
- data/lib/paysafe/util.rb +31 -0
- data/lib/paysafe/validate.rb +141 -0
- data/lib/paysafe/version.rb +5 -0
- data/lib/paysafe/webhooks.rb +84 -0
- data/lib/paysafe.rb +37 -0
- metadata +74 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 86fa2910971b84025251f547218faea391eab3d238dbd7a9b32b23a6125b8f9f
|
|
4
|
+
data.tar.gz: a64b80919e75c6600526a8ea018c1f0caca896b216ee0392cc2a9ca054bde709
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: eff41c6ab78683fe7d101808664585b9a6dbfd0d1ed2a5ef757801f0e82ca781ba460d7afc2227e46148a38bae347e8d03b9a80acfcf91846b6dacb69c672706
|
|
7
|
+
data.tar.gz: e61bee92fecfecaf468a295a06f19908a1f886f33edf507203cfea2c1a5c44d9ea06daaa223021416cbf0a476c87bbdea15caa40af153a58ad171ac82728a9ab
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/).
|
|
4
|
+
|
|
5
|
+
## [Unreleased]
|
|
6
|
+
|
|
7
|
+
## [0.1.0] - 2026-11-01
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- Client with sandbox/production selection from the key prefix, configurable base URL, timeout, retries, logger and HTTP client.
|
|
12
|
+
- Payments: create, list, get, cancel, wait for terminal state.
|
|
13
|
+
- Payment links: create, list, get, update.
|
|
14
|
+
- Control numbers: create, list, get, cancel.
|
|
15
|
+
- Refunds: create, list, get, wait for terminal state.
|
|
16
|
+
- Balance and transactions.
|
|
17
|
+
- Top-ups: create, list, get.
|
|
18
|
+
- Customers: list, get.
|
|
19
|
+
- Transfers: create, list, get, wait for terminal state.
|
|
20
|
+
- Webhook endpoints: list, create, get, update, delete.
|
|
21
|
+
- Events: list, get.
|
|
22
|
+
- Webhook signature verification and event construction.
|
|
23
|
+
- Typed models for every API schema, structured errors per documented code, cursor pagination helpers.
|
|
24
|
+
|
|
25
|
+
API version: 2026-09-07.
|
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 PaySafe
|
|
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,162 @@
|
|
|
1
|
+
# PaySafe Ruby SDK
|
|
2
|
+
|
|
3
|
+
Official Ruby library for the [PaySafe](https://paysafe.co.tz) payments API. Accept mobile-money payments in Tanzania, issue refunds, control numbers and payment links, move money between projects, and receive signed webhooks.
|
|
4
|
+
|
|
5
|
+
Part of the [PaySafe SDK directory](https://github.com/AmDev255/paysafe-sdks). API reference: https://paysafe.co.tz/docs.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- Every served PaySafe API operation (29 operations, 10 resources) with typed request and response models
|
|
10
|
+
- Sandbox and production selected automatically from the key prefix
|
|
11
|
+
- Safe retries that honour `Retry-After`, idempotency keys that survive retries, cursor pagination helpers
|
|
12
|
+
- Polling helpers that wait for a payment, refund or transfer to reach a terminal state
|
|
13
|
+
- Webhook signature verification with secret rotation support and constant-time comparison
|
|
14
|
+
- One structured exception per documented error code, every error carries the request id
|
|
15
|
+
- Configurable timeouts, base URL, logger and HTTP client
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
gem install paysafe-tz
|
|
21
|
+
# or in your Gemfile
|
|
22
|
+
gem "paysafe-tz"
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Requirements
|
|
26
|
+
|
|
27
|
+
Ruby 3.1 or newer. Uses `Net::HTTP` from the standard library.
|
|
28
|
+
|
|
29
|
+
## Authentication
|
|
30
|
+
|
|
31
|
+
Create a secret key in the dashboard under API keys. Test keys start with `paysafe_test_`, live keys with `paysafe_live_`. Keep keys on the server; never ship them in browsers or mobile apps. The SDK reads `PAYSAFE_SECRET_KEY` when no key is passed.
|
|
32
|
+
|
|
33
|
+
## Sandbox setup
|
|
34
|
+
|
|
35
|
+
Use a `paysafe_test_` key. The sandbox is the same API with a simulated provider; the last four digits of the customer phone choose the outcome (`0000` succeeds, `1111` is declined, `4444` expires, see the [Sandbox guide](https://paysafe.co.tz/docs/sandbox)).
|
|
36
|
+
|
|
37
|
+
## Production setup
|
|
38
|
+
|
|
39
|
+
Switch to a `paysafe_live_` key once your organisation is verified. Register a live webhook endpoint and add your server's address to the project's IP allowlist. Nothing else changes.
|
|
40
|
+
|
|
41
|
+
## Quickstart
|
|
42
|
+
|
|
43
|
+
```ruby
|
|
44
|
+
require "paysafe"
|
|
45
|
+
|
|
46
|
+
client = PaySafe::Client.new(api_key: ENV.fetch("PAYSAFE_SECRET_KEY")) # paysafe_test_… selects the sandbox
|
|
47
|
+
|
|
48
|
+
payment = client.payments.create(
|
|
49
|
+
{ amount: 10_000, customer: { phone: "+255712340000", name: "Amina Juma" }, reference: "order-8812" }, # TZS, integer
|
|
50
|
+
idempotency_key: "order-8812-attempt-1" # persist the key before calling
|
|
51
|
+
)
|
|
52
|
+
puts "#{payment.id} #{payment.status}" # 202 Accepted: still pending
|
|
53
|
+
|
|
54
|
+
done = client.payments.wait_for_terminal(payment.id) # or wait for the webhook
|
|
55
|
+
puts "Paid, net TZS #{done.net}" if done.successful?
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Supported API resources
|
|
59
|
+
|
|
60
|
+
| Resource | Operations |
|
|
61
|
+
|---|---|
|
|
62
|
+
| Payments | create, list, get, cancel, waitForTerminal |
|
|
63
|
+
| Payment links | create, list, get, update |
|
|
64
|
+
| Control numbers | create, list, get, cancel |
|
|
65
|
+
| Refunds | create, list, get, waitForTerminal |
|
|
66
|
+
| Top-ups | create, list, get |
|
|
67
|
+
| Balance | get, transactions |
|
|
68
|
+
| Customers | list, get |
|
|
69
|
+
| Transfers | create, list, get, waitForTerminal |
|
|
70
|
+
| Webhook endpoints | list, create, get, update, delete |
|
|
71
|
+
| Events | list, get |
|
|
72
|
+
| Webhooks | verifySignature, constructEvent |
|
|
73
|
+
|
|
74
|
+
Planned by PaySafe and not yet served (not included): `ping`, payouts (`createPayout`, `getPayout`), `rotateWebhookEndpointSecret`.
|
|
75
|
+
|
|
76
|
+
## Usage examples
|
|
77
|
+
|
|
78
|
+
Runnable programs live in [`examples/examples.rb`](examples/examples.rb) (see [`examples/README.md`](examples/README.md)): authentication, creating and polling a payment, listing with pagination, refunds, payment links, control numbers, transfers, webhook endpoints, events, customers and balance, and a webhook self-test, plus Rails and Sinatra handlers under `examples/webhooks/`.
|
|
79
|
+
|
|
80
|
+
Every resource takes a params Hash (symbol or string keys, snake_case like the API) and an optional options Hash (`idempotency_key`, `request_id`, `timeout`, `max_retries`, `headers`). Lists return a `PaySafe::Page` (Enumerable) with `data`, `has_more?`, `next_cursor`, `next_page` and `auto_paging_each`.
|
|
81
|
+
|
|
82
|
+
```ruby
|
|
83
|
+
# Pagination
|
|
84
|
+
client.payments.list(status: "succeeded", limit: 100).auto_paging_each { |p| }
|
|
85
|
+
|
|
86
|
+
# Top-ups: add money to your own balance (prompt: false opens the order for token, QR or hosted-page payment)
|
|
87
|
+
topup = client.topups.create(amount: 500_000, phone: "+255712345000", prompt: false, reference: "FLOAT-DEC-03")
|
|
88
|
+
topup = client.topups.get(topup.id) # topup.checkout holds pay_token, qr and url once the order is open
|
|
89
|
+
|
|
90
|
+
# Refunds
|
|
91
|
+
refund = client.refunds.create(payment: payment.id, amount: 5000, reason: "requested_by_customer")
|
|
92
|
+
|
|
93
|
+
# Payment links and control numbers
|
|
94
|
+
link = client.payment_links.create(title: "Workshop ticket", amount: 25_000)
|
|
95
|
+
number = client.control_numbers.create(payer_name: "Amina Juma", title: "Term 2 fees", amount: 450_000)
|
|
96
|
+
|
|
97
|
+
# Transfers, balance, customers, events
|
|
98
|
+
transfer = client.transfers.create(to: "merchant_shop", amount: 5000)
|
|
99
|
+
balance = client.balance.get
|
|
100
|
+
customer = client.customers.get("cus_…")
|
|
101
|
+
event = client.events.get("evt_…")
|
|
102
|
+
|
|
103
|
+
# Webhook endpoints (the secret is returned once)
|
|
104
|
+
endpoint = client.webhook_endpoints.create(url: "https://example.com/paysafe", events: ["payment.succeeded"])
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Responses are `PaySafe::ApiObject` instances (`Payment`, `Refund`, …): fields are readable as methods (`payment.amount`) or with `[]`; nested objects are plain Hashes with string keys; `to_h` and `to_json` give the raw data. Every object carries `last_response` with `status`, `request_id`, `rate_limit`, `idempotent_replayed?` and the `idempotency_key` that was sent. The client is thread-safe and uses `Net::HTTP` with certificate verification always on.
|
|
108
|
+
|
|
109
|
+
Retries: 429 and 503 wait for `Retry-After`; `idempotency_in_progress` waits one second; 5xx and network errors are retried only when the request is idempotent (GET, PATCH, DELETE, or a POST with an idempotency key). The SDK generates a UUID key for `payments.create`, `refunds.create`, `transfers.create` and `payments.cancel` when you do not pass one; pass your own key derived from the order to survive process restarts.
|
|
110
|
+
|
|
111
|
+
Security: ids, filters, headers and amounts are validated before any request (amounts must be Integers); path and query values are percent-encoded; the base URL must be https (plain http only for localhost or `allow_insecure_http: true`); redirects are never followed; response bodies are capped at 16 MB; JSON is parsed with `JSON.parse` only; the key never appears in exceptions, `inspect` or logs.
|
|
112
|
+
|
|
113
|
+
## Error handling
|
|
114
|
+
|
|
115
|
+
Every non-2xx response raises a subclass of `PaySafe::ApiError` chosen by the error code, with `status`, `code`, `message`, `request_id`, `param`, `details`, `doc_url`, `retry_after` and `rate_limit`:
|
|
116
|
+
|
|
117
|
+
```ruby
|
|
118
|
+
begin
|
|
119
|
+
client.payments.cancel(id)
|
|
120
|
+
rescue PaySafe::ValidationError => e # 400: fix the request (e.param names the field)
|
|
121
|
+
rescue PaySafe::InvalidStateError => e # 409: read the object and decide again
|
|
122
|
+
rescue PaySafe::RateLimitError => e # 429 after retries: back off e.retry_after seconds
|
|
123
|
+
rescue PaySafe::ApiError => e # anything else from the API; e.to_s is "code (status) message [request_id]"
|
|
124
|
+
rescue PaySafe::ApiConnectionError => e # no response at all (DNS, TLS, timeout: ApiTimeoutError)
|
|
125
|
+
rescue PaySafe::InvalidRequestError => e # rejected locally before any request was sent
|
|
126
|
+
end
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Classes: ValidationError, AuthenticationError, PermissionError (`ip_not_allowed?`, `observed_ip`), FeatureDisabledError, NotFoundError, InsufficientFundsError (`available`, `requested`), ConflictError, IdempotencyConflictError, IdempotencyInProgressError, InvalidStateError, RateLimitError (`scope`), ProviderError, ProviderUnavailableError, ServiceUnavailableError, InternalError, ApiConnectionError, ApiTimeoutError, ResponseTooLargeError, SignatureVerificationError, PollingTimeoutError, ConfigurationError, InvalidRequestError. Unknown codes map by HTTP status.
|
|
130
|
+
|
|
131
|
+
## Webhook integration
|
|
132
|
+
|
|
133
|
+
Verify the raw body before parsing it. `PaySafe::Webhooks.construct_event` checks the `PaySafe-Signature` header (HMAC-SHA256 over `t.body`, 300 s tolerance, constant-time comparison, several `v1=` values during rotation) and returns a typed `PaySafe::Event`:
|
|
134
|
+
|
|
135
|
+
```ruby
|
|
136
|
+
raw_body = request.raw_post # exact bytes, never params
|
|
137
|
+
begin
|
|
138
|
+
event = PaySafe::Webhooks.construct_event(ENV.fetch("PAYSAFE_WEBHOOK_SECRET"), raw_body, request.headers["PaySafe-Signature"])
|
|
139
|
+
mark_paid(event.payment.reference) if event.type == "payment.succeeded" # deduplicate on event.id first
|
|
140
|
+
rescue PaySafe::SignatureVerificationError
|
|
141
|
+
head :bad_request
|
|
142
|
+
end
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
`PaySafe::Webhooks.verify_signature` returns a boolean instead of raising; both accept an Array of secrets and a `tolerance:` keyword. `examples/webhooks/` holds a Rails controller and a Sinatra app, and `ruby examples/examples.rb verify-webhook` runs the self-test.
|
|
146
|
+
|
|
147
|
+
## Testing
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
bundle install
|
|
151
|
+
bundle exec rubocop && bundle exec rspec && gem build paysafe-tz.gemspec
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
Tests run offline against the fixtures in `tests/fixtures/` that are shared by every PaySafe SDK, with HTTP stubbed by WebMock. The integration specs run only when `PAYSAFE_SECRET_KEY` holds a `paysafe_test_` key (and optionally `PAYSAFE_BASE_URL`); they refuse live keys and use the sandbox phone suffixes documented at https://paysafe.co.tz/docs/sandbox. See `examples/README.md` for the runnable examples.
|
|
155
|
+
|
|
156
|
+
## Contributing
|
|
157
|
+
|
|
158
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md). Report security issues as described in [SECURITY.md](SECURITY.md).
|
|
159
|
+
|
|
160
|
+
## License
|
|
161
|
+
|
|
162
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module PaySafe
|
|
4
|
+
RateLimit = Struct.new(:limit, :remaining, :reset, keyword_init: true)
|
|
5
|
+
|
|
6
|
+
# The raw outcome of a request. Every model carries the one it came from in last_response.
|
|
7
|
+
class ApiResponse
|
|
8
|
+
attr_reader :status, :headers, :body, :idempotency_key
|
|
9
|
+
|
|
10
|
+
# headers: lower-cased names.
|
|
11
|
+
def initialize(status, headers, body, idempotency_key)
|
|
12
|
+
@status = status
|
|
13
|
+
@headers = headers.freeze
|
|
14
|
+
@body = body
|
|
15
|
+
@idempotency_key = idempotency_key
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
def request_id
|
|
19
|
+
headers["x-request-id"]
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def rate_limit
|
|
23
|
+
limit = headers["x-ratelimit-limit"]
|
|
24
|
+
remaining = headers["x-ratelimit-remaining"]
|
|
25
|
+
reset = headers["x-ratelimit-reset"]
|
|
26
|
+
return nil if limit.nil? && remaining.nil? && reset.nil?
|
|
27
|
+
|
|
28
|
+
to_i = ->(v) { v&.strip&.match?(/\A-?\d+\z/) ? v.to_i : nil }
|
|
29
|
+
RateLimit.new(limit: to_i.call(limit), remaining: to_i.call(remaining), reset: to_i.call(reset))
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def idempotent_replayed?
|
|
33
|
+
headers["idempotent-replayed"] == "true"
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# Seconds from Retry-After, or nil when absent.
|
|
37
|
+
def retry_after
|
|
38
|
+
value = headers["retry-after"]&.strip
|
|
39
|
+
return nil if value.nil? || value.empty?
|
|
40
|
+
return value.to_i if value.match?(/\A\d+\z/)
|
|
41
|
+
|
|
42
|
+
[(Time.httpdate(value) - Time.now).ceil, 0].max
|
|
43
|
+
rescue ArgumentError
|
|
44
|
+
nil
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def json
|
|
48
|
+
return nil if body.empty?
|
|
49
|
+
|
|
50
|
+
parsed = Util.parse_json(body)
|
|
51
|
+
parsed.is_a?(Hash) ? parsed : nil
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
end
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module PaySafe
|
|
4
|
+
# Client for one PaySafe project in one environment. Thread-safe.
|
|
5
|
+
class Client
|
|
6
|
+
DEFAULT_BASE_URL = "https://api.paysafe.co.tz"
|
|
7
|
+
DEFAULT_TIMEOUT = 30
|
|
8
|
+
DEFAULT_MAX_RETRIES = 4
|
|
9
|
+
MAX_RESPONSE_BYTES = 16 * 1024 * 1024
|
|
10
|
+
INITIAL_BACKOFF = 0.5
|
|
11
|
+
MAX_BACKOFF = 8.0
|
|
12
|
+
IN_PROGRESS_SLEEP = 1.0
|
|
13
|
+
METHODS = { "GET" => Net::HTTP::Get, "POST" => Net::HTTP::Post, "PATCH" => Net::HTTP::Patch, "DELETE" => Net::HTTP::Delete }.freeze
|
|
14
|
+
|
|
15
|
+
attr_reader :environment, :payments, :payment_links, :control_numbers, :refunds, :topups, :balance, :customers, :transfers,
|
|
16
|
+
:webhook_endpoints, :events
|
|
17
|
+
|
|
18
|
+
# api_key defaults to PAYSAFE_SECRET_KEY, base_url to PAYSAFE_BASE_URL. timeout is per attempt in seconds;
|
|
19
|
+
# max_retries counts retries after the first attempt. logger receives a LogRecord per attempt (never the key or bodies).
|
|
20
|
+
# sleeper and random are test hooks.
|
|
21
|
+
def initialize(api_key: nil, base_url: nil, timeout: DEFAULT_TIMEOUT, max_retries: DEFAULT_MAX_RETRIES, api_version: nil,
|
|
22
|
+
logger: nil, user_agent_suffix: nil, allow_insecure_http: false, sleeper: ->(s) { sleep(s) }, random: -> { Random.rand })
|
|
23
|
+
key = api_key || ENV.fetch("PAYSAFE_SECRET_KEY", nil)
|
|
24
|
+
raise ConfigurationError, "No API key given and PAYSAFE_SECRET_KEY is not set" if key.nil? || key.empty?
|
|
25
|
+
raise ConfigurationError, "API key contains invalid characters" unless Validate::API_KEY.match?(key)
|
|
26
|
+
|
|
27
|
+
@environment = if key.start_with?("paysafe_test_") then :test
|
|
28
|
+
elsif key.start_with?("paysafe_live_") then :live
|
|
29
|
+
else raise ConfigurationError, "API key must start with paysafe_test_ or paysafe_live_"
|
|
30
|
+
end
|
|
31
|
+
@api_key = key
|
|
32
|
+
@base_url = resolve_base_url(base_url, allow_insecure_http)
|
|
33
|
+
raise ConfigurationError, "timeout must be positive" unless timeout.is_a?(Numeric) && timeout.positive?
|
|
34
|
+
raise ConfigurationError, "max_retries must be zero or more" unless max_retries.is_a?(Integer) && max_retries >= 0
|
|
35
|
+
raise ConfigurationError, "user_agent_suffix contains control characters" if user_agent_suffix && Validate.control?(user_agent_suffix, false)
|
|
36
|
+
|
|
37
|
+
@timeout = timeout
|
|
38
|
+
@max_retries = max_retries
|
|
39
|
+
@api_version = api_version
|
|
40
|
+
@logger = logger
|
|
41
|
+
@sleeper = sleeper
|
|
42
|
+
@random = random
|
|
43
|
+
@user_agent = "paysafe-ruby/#{VERSION} (Ruby #{RUBY_VERSION}; #{RUBY_PLATFORM})#{" #{user_agent_suffix}" if user_agent_suffix}"
|
|
44
|
+
@payments = Resources::Payments.new(self)
|
|
45
|
+
@payment_links = Resources::PaymentLinks.new(self)
|
|
46
|
+
@control_numbers = Resources::ControlNumbers.new(self)
|
|
47
|
+
@refunds = Resources::Refunds.new(self)
|
|
48
|
+
@topups = Resources::Topups.new(self)
|
|
49
|
+
@balance = Resources::Balance.new(self)
|
|
50
|
+
@customers = Resources::Customers.new(self)
|
|
51
|
+
@transfers = Resources::Transfers.new(self)
|
|
52
|
+
@webhook_endpoints = Resources::WebhookEndpoints.new(self)
|
|
53
|
+
@events = Resources::Events.new(self)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def inspect
|
|
57
|
+
"#<PaySafe::Client environment=#{@environment} base_url=#{@base_url}>"
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# Low-level escape hatch: any method and path under /v1 with the raw ApiResponse.
|
|
61
|
+
def request(method, path, query: {}, body: nil, **opts)
|
|
62
|
+
send_request(method.to_s.upcase, "/#{path.to_s.delete_prefix("/")}", query, body, opts)
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# Sleeper used by the polling helpers.
|
|
66
|
+
def pause(seconds)
|
|
67
|
+
@sleeper.call(seconds)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def send_request(method, path, query, body, opts)
|
|
71
|
+
options = RequestOptions.from(opts)
|
|
72
|
+
raise InvalidRequestError, "Unsupported HTTP method #{method}" unless METHODS.key?(method)
|
|
73
|
+
|
|
74
|
+
target = "#{@base_url}#{path}"
|
|
75
|
+
first = true
|
|
76
|
+
query.each do |k, v|
|
|
77
|
+
next if v.nil?
|
|
78
|
+
|
|
79
|
+
k = k.to_s
|
|
80
|
+
v = v.to_s
|
|
81
|
+
Validate.query_value(k, v)
|
|
82
|
+
target << (first ? "?" : "&") << Util.encode(k) << "=" << Util.encode(v)
|
|
83
|
+
first = false
|
|
84
|
+
end
|
|
85
|
+
Validate.body_size(body) if body
|
|
86
|
+
retryable = %w[GET DELETE PATCH].include?(method) || !options.idempotency_key.nil?
|
|
87
|
+
max_attempts = 1 + (options.max_retries || @max_retries)
|
|
88
|
+
attempt = 0
|
|
89
|
+
loop do
|
|
90
|
+
attempt += 1
|
|
91
|
+
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
92
|
+
begin
|
|
93
|
+
response = send_once(method, target, body, options)
|
|
94
|
+
rescue ApiConnectionError => e
|
|
95
|
+
log(method, path, nil, attempt, started, nil, e.message)
|
|
96
|
+
raise if !retryable || attempt >= max_attempts || e.is_a?(ResponseTooLargeError)
|
|
97
|
+
|
|
98
|
+
@sleeper.call(backoff(attempt))
|
|
99
|
+
next
|
|
100
|
+
end
|
|
101
|
+
log(method, path, response.status, attempt, started, response.request_id, nil)
|
|
102
|
+
return response if response.status < 300
|
|
103
|
+
if response.status < 400
|
|
104
|
+
raise ApiError.new(status: response.status, code: "unexpected_redirect",
|
|
105
|
+
message: "The API answered with a redirect, which this SDK never follows",
|
|
106
|
+
request_id: response.request_id, headers: response.headers)
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
error = ErrorMapper.from_response(response)
|
|
110
|
+
delay = retry_delay(error, retryable, attempt)
|
|
111
|
+
raise error if delay.nil? || attempt >= max_attempts
|
|
112
|
+
|
|
113
|
+
@sleeper.call(delay)
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
private
|
|
118
|
+
|
|
119
|
+
def resolve_base_url(base_url, allow_insecure_http)
|
|
120
|
+
url = base_url || ENV.fetch("PAYSAFE_BASE_URL", nil)
|
|
121
|
+
url = DEFAULT_BASE_URL if url.nil? || url.empty?
|
|
122
|
+
raise ConfigurationError, "base_url contains whitespace or control characters" if url.match?(/\s/) || Validate.control?(url, false)
|
|
123
|
+
|
|
124
|
+
url = url.sub(%r{/+\z}, "").delete_suffix("/v1")
|
|
125
|
+
parsed = begin
|
|
126
|
+
URI.parse(url)
|
|
127
|
+
rescue URI::InvalidURIError
|
|
128
|
+
raise ConfigurationError, "base_url must be an absolute URL"
|
|
129
|
+
end
|
|
130
|
+
if !parsed.is_a?(URI::HTTP) || parsed.host.nil? || parsed.userinfo || parsed.query || parsed.fragment
|
|
131
|
+
raise ConfigurationError, "base_url must be an absolute URL without credentials, query or fragment"
|
|
132
|
+
end
|
|
133
|
+
unless parsed.scheme == "https" || (parsed.scheme == "http" && (allow_insecure_http || Validate.loopback?(parsed.host)))
|
|
134
|
+
raise ConfigurationError, "base_url must use https (plain http is only allowed for localhost or with allow_insecure_http)"
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
url
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
def retry_delay(error, retryable, attempt)
|
|
141
|
+
return IN_PROGRESS_SLEEP if error.code == "idempotency_in_progress"
|
|
142
|
+
return error.retry_after ? error.retry_after.to_f : backoff(attempt) if [429, 503].include?(error.status)
|
|
143
|
+
return backoff(attempt) if error.status >= 500 && error.code != "provider_error" && retryable
|
|
144
|
+
|
|
145
|
+
nil
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def backoff(attempt)
|
|
149
|
+
ceiling = [MAX_BACKOFF, INITIAL_BACKOFF * (2**[attempt - 1, 20].min)].min
|
|
150
|
+
@random.call * ceiling
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
def send_once(method, target, body, options)
|
|
154
|
+
uri = URI.parse(target)
|
|
155
|
+
req = METHODS[method].new(uri.request_uri)
|
|
156
|
+
req["Authorization"] = "Bearer #{@api_key}"
|
|
157
|
+
req["Accept"] = "application/json"
|
|
158
|
+
req["User-Agent"] = @user_agent
|
|
159
|
+
req["PaySafe-Version"] = @api_version if @api_version
|
|
160
|
+
req["Idempotency-Key"] = options.idempotency_key if options.idempotency_key
|
|
161
|
+
req["X-Request-ID"] = options.request_id if options.request_id
|
|
162
|
+
options.headers.each { |k, v| req[k] = v }
|
|
163
|
+
if body
|
|
164
|
+
req.body = body
|
|
165
|
+
req["Content-Type"] = "application/json"
|
|
166
|
+
end
|
|
167
|
+
timeout = options.timeout || @timeout
|
|
168
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
|
169
|
+
http.use_ssl = uri.scheme == "https"
|
|
170
|
+
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
|
|
171
|
+
http.open_timeout = [timeout, 10].min
|
|
172
|
+
http.read_timeout = timeout
|
|
173
|
+
http.write_timeout = timeout
|
|
174
|
+
begin
|
|
175
|
+
http.start { |conn| read_response(conn, req, options) }
|
|
176
|
+
rescue Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout => e
|
|
177
|
+
raise ApiTimeoutError, "Request to PaySafe timed out: #{e.class.name.split("::").last}"
|
|
178
|
+
rescue ResponseTooLargeError
|
|
179
|
+
raise
|
|
180
|
+
rescue SocketError, SystemCallError, OpenSSL::SSL::SSLError, IOError, Timeout::Error => e
|
|
181
|
+
raise ApiConnectionError, "Could not reach PaySafe: #{e.message}"
|
|
182
|
+
end
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
def read_response(conn, req, options)
|
|
186
|
+
result = nil
|
|
187
|
+
conn.request(req) do |res|
|
|
188
|
+
length = res["content-length"]
|
|
189
|
+
raise ResponseTooLargeError if length && length.to_i > MAX_RESPONSE_BYTES
|
|
190
|
+
|
|
191
|
+
body = +""
|
|
192
|
+
res.read_body do |chunk|
|
|
193
|
+
body << chunk
|
|
194
|
+
raise ResponseTooLargeError if body.bytesize > MAX_RESPONSE_BYTES
|
|
195
|
+
end
|
|
196
|
+
headers = res.to_hash.to_h { |k, v| [k.downcase, v.join(", ")] }
|
|
197
|
+
result = ApiResponse.new(res.code.to_i, headers, body.force_encoding(Encoding::UTF_8), options.idempotency_key)
|
|
198
|
+
end
|
|
199
|
+
result
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
def log(method, path, status, attempt, started, request_id, error)
|
|
203
|
+
return unless @logger
|
|
204
|
+
|
|
205
|
+
duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
|
|
206
|
+
@logger.call(LogRecord.new(http_method: method, path: path, status: status, attempt: attempt, duration: duration, request_id: request_id,
|
|
207
|
+
error: error))
|
|
208
|
+
end
|
|
209
|
+
end
|
|
210
|
+
end
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module PaySafe
|
|
4
|
+
# Base class for every error raised by this SDK.
|
|
5
|
+
class Error < StandardError; end
|
|
6
|
+
|
|
7
|
+
class ConfigurationError < Error; end
|
|
8
|
+
|
|
9
|
+
# Raised before any network call when the request fails local validation.
|
|
10
|
+
class InvalidRequestError < Error
|
|
11
|
+
attr_reader :param
|
|
12
|
+
|
|
13
|
+
def initialize(message, param = nil)
|
|
14
|
+
super(message)
|
|
15
|
+
@param = param
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# No HTTP response was received (DNS, TLS, socket errors).
|
|
20
|
+
class ApiConnectionError < Error; end
|
|
21
|
+
|
|
22
|
+
class ApiTimeoutError < ApiConnectionError; end
|
|
23
|
+
|
|
24
|
+
# The response body exceeded the SDK's size limit. Never retried.
|
|
25
|
+
class ResponseTooLargeError < ApiConnectionError
|
|
26
|
+
def initialize(message = "Response body exceeds the 16 MB limit")
|
|
27
|
+
super
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
class PollingTimeoutError < Error
|
|
32
|
+
attr_reader :last_seen
|
|
33
|
+
|
|
34
|
+
def initialize(message, last_seen)
|
|
35
|
+
super(message)
|
|
36
|
+
@last_seen = last_seen
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
class SignatureVerificationError < Error
|
|
41
|
+
MISSING_HEADER = "missing_header"
|
|
42
|
+
MALFORMED_HEADER = "malformed_header"
|
|
43
|
+
TIMESTAMP_OUTSIDE_TOLERANCE = "timestamp_outside_tolerance"
|
|
44
|
+
SIGNATURE_MISMATCH = "signature_mismatch"
|
|
45
|
+
INVALID_PAYLOAD = "invalid_payload"
|
|
46
|
+
|
|
47
|
+
attr_reader :reason
|
|
48
|
+
|
|
49
|
+
def initialize(reason, message)
|
|
50
|
+
super(message)
|
|
51
|
+
@reason = reason
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# Any non-2xx response from the API. Subclasses exist for every documented error code.
|
|
56
|
+
class ApiError < Error
|
|
57
|
+
attr_reader :status, :code, :request_id, :param, :details, :doc_url, :headers, :retry_after, :rate_limit
|
|
58
|
+
|
|
59
|
+
def initialize(status:, code:, message:, request_id: nil, param: nil, details: nil, doc_url: nil, headers: {}, retry_after: nil,
|
|
60
|
+
rate_limit: nil)
|
|
61
|
+
super(message)
|
|
62
|
+
@raw_message = message
|
|
63
|
+
@status = status
|
|
64
|
+
@code = code
|
|
65
|
+
@request_id = request_id
|
|
66
|
+
@param = param
|
|
67
|
+
@details = details
|
|
68
|
+
@doc_url = doc_url
|
|
69
|
+
@headers = headers
|
|
70
|
+
@retry_after = retry_after
|
|
71
|
+
@rate_limit = rate_limit
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# Whether the documented retry policy allows retrying with the same idempotency key.
|
|
75
|
+
def retryable?
|
|
76
|
+
status == 429 || status == 503 || code == "idempotency_in_progress" || (status >= 500 && code != "provider_error")
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def message
|
|
80
|
+
@raw_message
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
def to_s
|
|
84
|
+
"#{code} (#{status}) #{@raw_message} [#{request_id || "no request id"}]"
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
def inspect
|
|
88
|
+
"#<#{self.class.name} #{self}>"
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
class ValidationError < ApiError; end
|
|
93
|
+
class AuthenticationError < ApiError; end
|
|
94
|
+
|
|
95
|
+
class PermissionError < ApiError
|
|
96
|
+
def ip_not_allowed?
|
|
97
|
+
%w[ip_not_allowed ip_allowlist_empty].include?(details&.dig("code"))
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
def observed_ip
|
|
101
|
+
details&.dig("ip")
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
class FeatureDisabledError < ApiError; end
|
|
106
|
+
class NotFoundError < ApiError; end
|
|
107
|
+
|
|
108
|
+
class InsufficientFundsError < ApiError
|
|
109
|
+
def available
|
|
110
|
+
details&.dig("available")
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def requested
|
|
114
|
+
details&.dig("requested")
|
|
115
|
+
end
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
class ConflictError < ApiError; end
|
|
119
|
+
class IdempotencyConflictError < ConflictError; end
|
|
120
|
+
class IdempotencyInProgressError < ConflictError; end
|
|
121
|
+
class InvalidStateError < ConflictError; end
|
|
122
|
+
|
|
123
|
+
class RateLimitError < ApiError
|
|
124
|
+
def scope
|
|
125
|
+
details&.dig("scope")
|
|
126
|
+
end
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
class ProviderError < ApiError; end
|
|
130
|
+
class ProviderUnavailableError < ApiError; end
|
|
131
|
+
class ServiceUnavailableError < ApiError; end
|
|
132
|
+
class InternalError < ApiError; end
|
|
133
|
+
|
|
134
|
+
module ErrorMapper
|
|
135
|
+
BY_CODE = {
|
|
136
|
+
"validation_error" => ValidationError,
|
|
137
|
+
"authentication_error" => AuthenticationError,
|
|
138
|
+
"permission_error" => PermissionError,
|
|
139
|
+
"feature_disabled" => FeatureDisabledError,
|
|
140
|
+
"not_found" => NotFoundError,
|
|
141
|
+
"insufficient_funds" => InsufficientFundsError,
|
|
142
|
+
"conflict" => ConflictError,
|
|
143
|
+
"idempotency_conflict" => IdempotencyConflictError,
|
|
144
|
+
"idempotency_in_progress" => IdempotencyInProgressError,
|
|
145
|
+
"invalid_state" => InvalidStateError,
|
|
146
|
+
"rate_limited" => RateLimitError,
|
|
147
|
+
"provider_error" => ProviderError,
|
|
148
|
+
"provider_unavailable" => ProviderUnavailableError,
|
|
149
|
+
"service_unavailable" => ServiceUnavailableError
|
|
150
|
+
}.freeze
|
|
151
|
+
|
|
152
|
+
BY_STATUS = {
|
|
153
|
+
400 => ValidationError, 401 => AuthenticationError, 402 => InsufficientFundsError, 403 => PermissionError,
|
|
154
|
+
404 => NotFoundError, 409 => ConflictError, 429 => RateLimitError, 503 => ServiceUnavailableError
|
|
155
|
+
}.freeze
|
|
156
|
+
|
|
157
|
+
def self.from_response(response)
|
|
158
|
+
envelope = response.json&.dig("error")
|
|
159
|
+
envelope = nil unless envelope.is_a?(Hash)
|
|
160
|
+
code = "unknown"
|
|
161
|
+
message = "HTTP #{response.status} from the PaySafe API"
|
|
162
|
+
request_id = response.request_id
|
|
163
|
+
param = details = doc_url = nil
|
|
164
|
+
if envelope
|
|
165
|
+
code = envelope["code"] if envelope["code"].is_a?(String)
|
|
166
|
+
message = envelope["message"] if envelope["message"].is_a?(String)
|
|
167
|
+
request_id = envelope["request_id"] if envelope["request_id"].is_a?(String)
|
|
168
|
+
param = envelope["param"] if envelope["param"].is_a?(String)
|
|
169
|
+
details = envelope["details"] if envelope["details"].is_a?(Hash)
|
|
170
|
+
doc_url = envelope["doc_url"] if envelope["doc_url"].is_a?(String)
|
|
171
|
+
elsif !response.body.empty?
|
|
172
|
+
details = { "raw" => response.body[0, 4096] }
|
|
173
|
+
end
|
|
174
|
+
klass = BY_CODE[code] || BY_STATUS[response.status] || (response.status >= 500 ? InternalError : ApiError)
|
|
175
|
+
klass.new(status: response.status, code: code, message: message, request_id: request_id, param: param, details: details,
|
|
176
|
+
doc_url: doc_url, headers: response.headers, retry_after: response.retry_after, rate_limit: response.rate_limit)
|
|
177
|
+
end
|
|
178
|
+
end
|
|
179
|
+
end
|