wajub 1.3.0 → 1.4.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3a5524dcd4b29eab3e66cc9c5fb1890324ee8fa4b7b090f1117d4feb4492dee7
4
- data.tar.gz: a863c218296f0ed42c0b89198b612519ad3ec85589829b189aaad40564f3ef98
3
+ metadata.gz: 39630ba4b905b7b327497eed4892d544935f43cbec061955453fa13663519da9
4
+ data.tar.gz: b51e523f15ba315aeaef028067886c121a87232d8d5d7010e3f26f185cf76ca6
5
5
  SHA512:
6
- metadata.gz: 92e45ed29b1f73f55eb0d43bd4bf2933ae744a622605f028fc017efc7af842f2462bd9e0d3aafa8c84bc54f6ce03da1d8dc1c15c5c205e6052effe1a9ed9603b
7
- data.tar.gz: 4decf56f623ce500d86109d640608620c654c862f3bfdf948f2587e7c6aa7bb4dcb1ddf2dddbf80a9fbc49300a4ab0a383fb8866d800894dc76edbc60ccd1d60
6
+ metadata.gz: a95b30792066aaf19bbded87a2ce674dd2548ecb8b785a491d348f9661d701238be99effd522bbc6ed923877ada5df8e58303f03fc946e72f650913cdb26596b
7
+ data.tar.gz: 56fa9971254484f578696c290837f1b9ca73025f48dc38e872aee5ca397e2b1242fd1788a110d5cae77f49b3a50e3582c2b7683ab623bd10827858bf1e65ef64
data/CHANGELOG.md CHANGED
@@ -7,13 +7,52 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
7
7
 
8
8
  ---
9
9
 
10
+ ## [1.4.0] — 2026-10-15
11
+
12
+ ### Added
13
+ - **`field_errors` on API errors, every validation message of each field.** A
14
+ `422` can give a field several messages; `errors` keeps only the first one.
15
+ `e.field_errors['amount']` lists them all, in the order the API sent them.
16
+ `errors` is unchanged.
17
+ - **`invoices.send_invoice`** sends an invoice to its customer. `invoices.send`
18
+ still does, but it is also the name of Ruby's `send`: prefer `send_invoice`.
19
+
20
+ ### Changed
21
+ - **`invoices.send` with a Symbol calls that method**, as Ruby's `send` does,
22
+ for code and libraries that call methods by name.
23
+ `invoices.send(:retrieve, id)` used to try to send an invoice whose id is
24
+ `retrieve`. A String is still an invoice id, whatever it reads.
25
+ - **A `nil` id raises `ArgumentError`** before anything is sent. It used to
26
+ send the request without the id: `payments.retrieve(nil)` listed payments.
27
+
28
+ ### Deprecated
29
+ - **`listen.config` and `listen.auth`.** The API no longer offers them. To
30
+ receive webhooks on your machine, forward them with the Wajub CLI:
31
+ `wajub listen`. Both warn when Ruby shows deprecation warnings
32
+ (`-W:deprecated`).
33
+
34
+ ### Fixed
35
+ - **A space in an id goes out as `%20`.** It went out as `+`, which the API
36
+ reads as a plus sign.
37
+ - **`webhooks.construct_event` keeps the replay window.** A tolerance of `0` or
38
+ less switched the timestamp check off, so an old delivery sent again was
39
+ accepted. A tolerance that is not a positive number now keeps the default of
40
+ 300 seconds; `nil` used to raise `NoMethodError`.
41
+
42
+ ### Security
43
+ - **An id that is not a Wajub id is refused before anything is sent.** If an
44
+ id you pass can come from a URL or a form, a call could act on another
45
+ resource of your account: `customers.delete('cus_1/tax_ids/txi_1')` deleted a
46
+ tax ID. An id that is empty, `.` or `..`, or contains `/`, now raises
47
+ `ArgumentError`. Wajub ids never take these forms, so valid calls are
48
+ unchanged.
49
+
10
50
  ## [1.3.0] — 2026-10-12
11
51
 
12
- 1.2.1 was never published to RubyGems: its changes ship in this release.
52
+ 1.2.1 was not published to RubyGems: its changes ship in this release.
13
53
 
14
54
  ### Added
15
- - The tax and Shield methods the other server SDKs already had, with the
16
- same paths and the same results as the Python SDK:
55
+ - Tax and Shield methods:
17
56
  - `tax.reports`, `tax.list_codes`, `tax.retrieve_code`, `tax.jurisdictions`,
18
57
  `tax.thresholds` and `tax.threshold_alerts`;
19
58
  - `tax.list_registrations` (a page), `tax.create_registration`,
@@ -25,10 +64,7 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
25
64
  The README listed them, and calling one raised `NoMethodError`.
26
65
 
27
66
  ### Fixed
28
- - `customers.delete_tax_id` called `DELETE /customers/%2Fcustomers%2F…` and
29
- answered `404`: the nested path went through the resource's own `delete`,
30
- which takes an id and encodes it as one path segment. It now calls
31
- `DELETE /customers/{id}/tax_ids/{tax_id}`.
67
+ - `customers.delete_tax_id` deletes the customer's tax id. It answered `404`.
32
68
  - `webhooks.construct_event` with a missing `X-Wajub-Signature` or
33
69
  `X-Wajub-Timestamp` header (`nil`) raised `NoMethodError`, which a handler
34
70
  rescuing `WebhookSignatureVerificationError` let through as a 500. It now
@@ -36,16 +72,12 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
36
72
  number.
37
73
 
38
74
  ### Changed
39
- - **The `409` for an `Idempotency-Key` still being processed is retried.** A
40
- call sent again after a timeout can reach the API while the first one is still
41
- running; the API answers `409` with `errors.idempotency_key`. The client now
42
- waits 2 then 4 seconds and asks again with the same key, within its usual 2
43
- retries, and returns the first request's result. Every other `409` is still
44
- raised at once.
75
+ - **A create sent again with the same idempotency key while the first is still
76
+ running** now returns the first request's result instead of a `409` error.
45
77
 
46
78
  ## [1.2.0] — 2026-10-01
47
79
 
48
- Tagged, never published to RubyGems. Its one change ships with 1.3.0.
80
+ Not published to RubyGems. Its one change ships with 1.3.0.
49
81
 
50
82
  ### Removed
51
83
  - `payments.initialize_payment`, an alias of `payments.create`. Call `create`.
data/README.md CHANGED
@@ -4,33 +4,24 @@
4
4
  [![Ruby](https://img.shields.io/badge/Ruby-3.1%2B-red)](https://www.ruby-lang.org/)
5
5
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
6
6
 
7
- Official **server-side** SDK for the [Wajub merchant API](https://docs.wajub.com). Accept mobile-money and card payments across Africa with a Stripe-inspired, resource-oriented client.
7
+ Official server-side SDK for the [Wajub API](https://docs.wajub.com): create payments, confirm them, pay out and verify webhooks from your Ruby backend.
8
8
 
9
- Use **[Wajub.js](https://docs.wajub.com/libraries/components/js)** for embedded checkout in the browser. Use this SDK on your backend with a secret (`sk_`) or restricted (`rk_`) API key — never expose secret keys in client-side code.
10
-
11
- ## Features
12
-
13
- - Resource-oriented API (`client.payments`, `client.customers`, …)
14
- - Automatic `Idempotency-Key` on mutating requests (override per call)
15
- - Typed errors per HTTP status (`AuthenticationError`, `RateLimitError`, …)
16
- - Automatic retries on 429 and 5xx (max 2, exponential backoff)
17
- - Page-based pagination with `auto_paging_each` and `next_page`
18
- - Webhook signature verification (HMAC-SHA256, timestamp tolerance)
19
- - Zero third-party runtime dependencies (stdlib only)
9
+ It runs on your server with a secret (`sk.…`, `sk_test.…`) or restricted (`rk.…`, `rk_test.…`) API key. Never expose these keys in client-side code: in the browser, use [Wajub.js](https://docs.wajub.com/libraries/components/js) with your publishable key (`pk.…`, `pk_test.…`).
20
10
 
21
11
  ## Requirements
22
12
 
23
13
  | Requirement | Version |
24
14
  |-------------|---------|
25
15
  | Ruby | 3.1 or later |
26
- | Dependencies | Standard library only (`net/http`, `openssl`, `json`) |
16
+
17
+ No other gem is needed.
27
18
 
28
19
  ## Installation
29
20
 
30
21
  Add to your Gemfile:
31
22
 
32
23
  ```ruby
33
- gem 'wajub', '~> 1.3'
24
+ gem 'wajub', '~> 1.4'
34
25
  ```
35
26
 
36
27
  Or install directly:
@@ -41,67 +32,94 @@ gem install wajub
41
32
 
42
33
  ## Quick start
43
34
 
44
- Amounts are passed in the **smallest currency unit** (e.g. cents for EUR/USD; whole francs for XAF).
45
-
46
- ### Redirect checkout
35
+ Amounts are in the currency's **main unit**: `12.50` for GHS 12.50, `5000` for XAF 5,000.
47
36
 
48
37
  ```ruby
49
38
  require 'wajub'
50
39
 
51
- client = Wajub::Client.new(api_key: ENV['WAJUB_API_KEY'])
40
+ client = Wajub::Client.new(
41
+ api_key: ENV.fetch('WAJUB_API_KEY'),
42
+ webhook_secret: ENV.fetch('WAJUB_WEBHOOK_SECRET')
43
+ )
52
44
 
53
45
  payment = client.payments.create(
54
46
  'amount' => 15_000,
55
47
  'currency' => 'XAF',
56
48
  'email' => 'buyer@example.com',
49
+ 'reference' => 'order-1042',
57
50
  'callback' => 'https://shop.example.com/order/complete'
58
51
  )
59
52
 
60
- puts payment.authorization_url
53
+ # Redirect the customer to payment.authorization_url,
54
+ # or mount payment.authorization_token with Wajub.js in your page.
61
55
  ```
62
56
 
63
- ### Inline / overlay (embed token)
57
+ Then confirm the result on your server: handle the `payment.succeeded` webhook, or call `client.payments.retrieve(payment.id)`.
64
58
 
65
- ```ruby
66
- embed = client.payments.create(
67
- 'amount' => 15_000,
68
- 'currency' => 'XAF',
69
- 'metadata' => { 'mode' => 'embed' }
70
- )
59
+ Parameters go in as a hash with the API's field names. `create` and `retrieve` return an object whose fields read as methods (`payment.authorization_url`) or with brackets (`payment['authorization_url']`). Use brackets for an optional field: a method raises `NoMethodError` when the field is absent, brackets return `nil`.
60
+
61
+ ## Configuration
71
62
 
72
- # Pass to Wajub.js: embed.authorization_token
63
+ | Keyword | Description |
64
+ |---------|-------------|
65
+ | `api_key` | Secret or restricted API key (`sk.…`, `sk_test.…`, `rk.…`, `rk_test.…`). Falls back to `WAJUB_API_KEY`. |
66
+ | `webhook_secret` | Webhook signing secret (`whsec_…`), needed only for `webhooks.construct_event`. Falls back to `WAJUB_WEBHOOK_SECRET`. |
67
+
68
+ An empty key raises `ArgumentError` when the client is built.
69
+
70
+ ## Resources
71
+
72
+ | Purpose | Property | Methods |
73
+ |---------|----------|---------|
74
+ | Payments | `client.payments` | `create`, `retrieve`, `list`, `cancel`, `process`, `process_split`, `list_refunds` |
75
+ | Refunds | `client.refunds` | `create`, `retrieve`, `list` |
76
+ | Customers | `client.customers` | `create`, `retrieve`, `update`, `delete`, `list`, `block`, `unblock`, `activate`, `deactivate`, `list_tax_ids`, `create_tax_id`, `delete_tax_id` |
77
+ | Payment links | `client.links` | `create`, `retrieve`, `update`, `delete`, `list` |
78
+ | Invoices | `client.invoices` | `create`, `retrieve`, `update`, `delete`, `list`, `send_invoice`, `mark_paid`, `cancel` |
79
+ | Payouts | `client.transfers` | `create`, `retrieve`, `list` |
80
+ | Payout recipients | `client.beneficiaries` | `create`, `retrieve`, `update`, `delete`, `list` |
81
+ | Destination checks | `client.identity` | `resolve`, `validate` |
82
+ | Balance | `client.balance` | `retrieve` |
83
+ | Disputes | `client.disputes` | `list`, `retrieve`, `submit_evidence`, `accept`, `close`, `send_message` |
84
+ | Events | `client.events` | `list`, `retrieve`, `resend` |
85
+ | Webhook endpoints | `client.webhook_endpoints` | `create`, `retrieve`, `update`, `delete`, `list`, `rotate_secret` |
86
+ | Webhook verification | `client.webhooks` | `construct_event` |
87
+ | Connected accounts (Sync) | `client.accounts` | `create`, `retrieve`, `update`, `delete`, `list`, `regenerate_token` |
88
+ | Tax | `client.tax` | `get_settings`, `update_settings`, `rates`, `calculate`, `reports`, `list_codes`, `retrieve_code`, `list_registrations`, `create_registration`, `retrieve_registration`, `update_registration`, `delete_registration`, `jurisdictions`, `thresholds`, `threshold_alerts` |
89
+ | Fraud (Shield) | `client.shield` | `get_settings`, `update_settings`, `stats`, `list_blocklist`, `add_to_blocklist`, `remove_from_blocklist` |
90
+ | Reference data | `client.global` | `ping`, `channels`, `countries`, `currencies` |
91
+
92
+ ## Acting for a connected account
93
+
94
+ Pass the connected account with `sync` in the call's options:
95
+
96
+ ```ruby
97
+ client.payments.create(params, Wajub::RequestOptions.new(sync: 'acct_sync_ref'))
73
98
  ```
74
99
 
75
- `create()` and `retrieve()` return a typed `Payment` object — prefer method access (`payment.authorization_url`). List pages from `list()` yield plain hashes; bracket syntax (`payment['…']`) remains available on typed objects.
100
+ ## Webhooks
76
101
 
77
- ## Rails
102
+ Pass the **raw request body**, not `params`, with the `X-Wajub-Signature` and `X-Wajub-Timestamp` headers. In Rails, build the client once in an initializer and share it:
78
103
 
79
104
  ```ruby
80
105
  # config/initializers/wajub.rb
81
- WajubClient = Wajub::Client.new(
82
- api_key: Rails.application.credentials.dig(:wajub, :api_key) || ENV['WAJUB_API_KEY'],
83
- webhook_secret: ENV['WAJUB_WEBHOOK_SECRET']
84
- )
106
+ WAJUB = Wajub::Client.new # reads WAJUB_API_KEY and WAJUB_WEBHOOK_SECRET
85
107
  ```
86
108
 
87
- ### Webhook controller
88
-
89
- Use the **raw request body**:
90
-
91
109
  ```ruby
92
- class WebhooksController < ApplicationController
110
+ class WajubWebhooksController < ApplicationController
93
111
  skip_before_action :verify_authenticity_token
94
112
 
95
- def wajub
96
- event = WajubClient.webhooks.construct_event(
97
- request.body.read, # raw body — not params
113
+ def create
114
+ event = WAJUB.webhooks.construct_event(
115
+ request.raw_post,
98
116
  request.headers['X-Wajub-Signature'],
99
117
  request.headers['X-Wajub-Timestamp']
100
118
  )
101
119
 
102
120
  case event['event']
103
121
  when 'payment.succeeded'
104
- # fulfill order
122
+ # fulfil the order
105
123
  end
106
124
 
107
125
  head :ok
@@ -111,82 +129,26 @@ class WebhooksController < ApplicationController
111
129
  end
112
130
  ```
113
131
 
114
- ## Configuration
115
-
116
- | Variable | Description |
117
- |----------|-------------|
118
- | `WAJUB_API_KEY` | Secret or restricted API key (`sk_`, `sk_test.`, `rk_`, …) |
119
- | `WAJUB_WEBHOOK_SECRET` | Webhook signing secret (`whsec_`) for `construct_event()` |
120
-
121
- Test mode is selected by your API key prefix (`sk_test.…`), not by the API URL. Production calls always go to `https://api.wajub.com`.
122
-
123
- ## Resources (merchant API)
124
-
125
- | Property | Methods |
126
- |----------|---------|
127
- | `client.global` | `ping`, `channels`, `countries`, `currencies` |
128
- | `client.payments` | `create`, `retrieve`, `list`, `cancel`, `process`, `process_split`, `list_refunds` |
129
- | `client.customers` | `create`, `retrieve`, `update`, `delete`, `list`, `block`, `unblock`, `activate`, `deactivate`, `list_tax_ids`, `create_tax_id`, `delete_tax_id` |
130
- | `client.refunds` | `create`, `retrieve`, `list` |
131
- | `client.transfers` | `create`, `retrieve`, `list` |
132
- | `client.beneficiaries` | `create`, `retrieve`, `update`, `delete`, `list` |
133
- | `client.links` | `create`, `retrieve`, `update`, `delete`, `list` |
134
- | `client.invoices` | `create`, `retrieve`, `update`, `delete`, `list`, `send`, `mark_paid`, `cancel` |
135
- | `client.accounts` | `create`, `retrieve`, `update`, `delete`, `list`, `regenerate_token` |
136
- | `client.webhook_endpoints` | `create`, `retrieve`, `update`, `delete`, `list`, `rotate_secret` |
137
- | `client.balance` | `retrieve` |
138
- | `client.events` | `list`, `retrieve`, `resend` |
139
- | `client.disputes` | `list`, `retrieve`, `submit_evidence`, `accept`, `close`, `send_message` |
140
- | `client.identity` | `resolve`, `validate` |
141
- | `client.tax` | `get_settings`, `update_settings`, `rates`, `calculate`, `reports`, `list_codes`, `retrieve_code`, `list_registrations`, `create_registration`, `retrieve_registration`, `update_registration`, `delete_registration`, `jurisdictions`, `thresholds`, `threshold_alerts` |
142
- | `client.shield` | `get_settings`, `update_settings`, `stats`, `list_blocklist`, `add_to_blocklist`, `remove_from_blocklist` |
143
- | `client.listen` | `config`, `auth` |
144
- | `client.webhooks` | `construct_event` (local — no HTTP) |
145
-
146
- ## Sync (Connect)
147
-
148
- ```ruby
149
- client.payments.create(params, Wajub::RequestOptions.new(sync: 'acct_sync_ref'))
150
- ```
151
-
152
- ## Webhooks
153
-
154
- ```ruby
155
- begin
156
- event = client.webhooks.construct_event(
157
- request.body.read, # String — raw body bytes
158
- request.env['HTTP_X_WAJUB_SIGNATURE'],
159
- request.env['HTTP_X_WAJUB_TIMESTAMP']
160
- )
161
- rescue Wajub::WebhookSignatureVerificationError
162
- halt 400
163
- end
164
-
165
- case event['event']
166
- when 'payment.succeeded'
167
- # fulfill order
168
- end
169
- ```
170
-
171
- During local development, use the [Wajub CLI](https://github.com/wajubhq/wajub-cli) to forward webhooks to your machine.
132
+ A delivery that does not verify, or that lacks one of the headers, raises `Wajub::WebhookSignatureVerificationError`. If your server's clock drifts, pass a tolerance in seconds as a fourth argument.
172
133
 
173
134
  ## Pagination
174
135
 
136
+ `list` returns a page you can walk one page at a time, or iterate across all pages. Its rows are plain hashes:
137
+
175
138
  ```ruby
176
139
  page = client.payments.list('per_page' => 50)
140
+ puts page.data, page.meta, page.has_more
141
+
142
+ next_page = page.next_page if page.has_more
177
143
 
178
144
  page.auto_paging_each do |payment|
179
145
  puts "#{payment['id']} #{payment['status']}"
180
146
  end
181
-
182
- # Manual page control
183
- first = client.payments.list
184
- second = first.next_page if first.has_more
185
147
  ```
186
148
 
187
149
  ## Idempotency
188
150
 
189
- POST and PUT requests automatically receive an `Idempotency-Key` header. Pass your own:
151
+ Temporary failures are retried for you. To make a create safe to repeat on your side too, after a restart or in a job retry, pass your own key:
190
152
 
191
153
  ```ruby
192
154
  client.payments.create(
@@ -197,28 +159,41 @@ client.payments.create(
197
159
 
198
160
  ## Error handling
199
161
 
162
+ API errors raise a subclass of `Wajub::WajubError`:
163
+
200
164
  ```ruby
201
165
  begin
202
166
  client.payments.create(params)
203
167
  rescue Wajub::InvalidRequestError => e
204
- puts e.errors # field-level validation errors
168
+ puts e.field_errors # every validation message, by field
205
169
  rescue Wajub::AuthenticationError
206
- # 401 — bad API key
207
- rescue Wajub::RateLimitError
208
- # 429 — back off and retry
170
+ # check your API key
171
+ rescue Wajub::RateLimitError => e
172
+ puts e.retry_after # seconds to wait
173
+ rescue Wajub::WajubError => e
174
+ puts e.code, e.http_status, e.message
209
175
  end
210
176
  ```
211
177
 
212
- ## Development
178
+ | Class | Raised on |
179
+ |-------|-----------|
180
+ | `Wajub::AuthenticationError` | `401` |
181
+ | `Wajub::PermissionError` | `403` |
182
+ | `Wajub::NotFoundError` | `404` |
183
+ | `Wajub::InvalidRequestError` | `400`, `422` |
184
+ | `Wajub::RateLimitError` | `429`, with `retry_after` in seconds |
185
+ | `Wajub::ApiConnectionError` | No response: network error or timeout |
186
+ | `Wajub::WajubError` | Any other error status, and the parent of all of the above |
213
187
 
214
- ```bash
215
- bundle install
216
- bundle exec rake test
217
- ```
188
+ Every error carries `message`, `code`, `http_status`, `field_errors` (every validation message of each field), `errors` (the first message of each field) and `raw` (the response body).
189
+
190
+ ## Testing
191
+
192
+ Use a sandbox key (`sk_test.…`): the key chooses the environment, and no real money moves. The test phone numbers and cards are on [Test scenarios](https://docs.wajub.com/developer-tools/testing/test-scenarios). To receive webhooks on your machine, forward them with the [Wajub CLI](https://docs.wajub.com/developer-tools/cli/listen).
218
193
 
219
194
  ## Documentation & support
220
195
 
221
- - Full API reference: [docs.wajub.com/libraries/sdks/ruby](https://docs.wajub.com/libraries/sdks/ruby)
196
+ - Documentation: [docs.wajub.com/libraries/sdks/ruby](https://docs.wajub.com/libraries/sdks/ruby)
222
197
  - Report issues: [github.com/wajubhq/wajub-ruby/issues](https://github.com/wajubhq/wajub-ruby/issues)
223
198
 
224
199
  ## License
data/lib/wajub/errors.rb CHANGED
@@ -2,13 +2,16 @@
2
2
 
3
3
  module Wajub
4
4
  class WajubError < StandardError
5
- attr_reader :code, :http_status, :errors, :raw
5
+ # errors holds the first message of each field; field_errors holds every
6
+ # message of each field, as an Array, in the order the API sent them.
7
+ attr_reader :code, :http_status, :errors, :field_errors, :raw
6
8
 
7
- def initialize(message, code:, http_status:, errors: nil, raw: nil)
9
+ def initialize(message, code:, http_status:, errors: nil, raw: nil, field_errors: nil)
8
10
  super(message)
9
11
  @code = code
10
12
  @http_status = http_status
11
13
  @errors = errors
14
+ @field_errors = field_errors || (errors.transform_values { |value| value.is_a?(Array) ? value : [value] } if errors.is_a?(Hash))
12
15
  @raw = raw
13
16
  end
14
17
  end
@@ -21,15 +24,15 @@ module Wajub
21
24
  class RateLimitError < WajubError
22
25
  attr_reader :retry_after
23
26
 
24
- def initialize(message, code:, http_status:, errors: nil, raw: nil, retry_after: nil)
25
- super(message, code: code, http_status: http_status, errors: errors, raw: raw)
27
+ def initialize(message, code:, http_status:, errors: nil, raw: nil, retry_after: nil, field_errors: nil)
28
+ super(message, code: code, http_status: http_status, errors: errors, raw: raw, field_errors: field_errors)
26
29
  @retry_after = retry_after
27
30
  end
28
31
  end
29
32
 
30
33
  class ApiConnectionError < WajubError
31
- def initialize(message, code: 'network_error', http_status: 0, errors: nil, raw: nil)
32
- super(message, code: code, http_status: http_status, errors: errors, raw: raw)
34
+ def initialize(message, code: 'network_error', http_status: 0, errors: nil, raw: nil, field_errors: nil)
35
+ super(message, code: code, http_status: http_status, errors: errors, raw: raw, field_errors: field_errors)
33
36
  end
34
37
  end
35
38
 
@@ -41,15 +44,21 @@ module Wajub
41
44
  def from_response(status, body, retry_after: nil)
42
45
  message = body['message'] || "Request failed (#{status})"
43
46
  code = body['error_code'] || body['code'] || "http_#{status}"
44
- field_errors = parse_field_errors(body['errors'])
47
+ details = {
48
+ code: code,
49
+ http_status: status,
50
+ errors: parse_field_errors(body['errors']),
51
+ field_errors: parse_all_field_errors(body['errors']),
52
+ raw: body
53
+ }
45
54
 
46
55
  case status
47
- when 401 then AuthenticationError.new(message, code: code, http_status: status, errors: field_errors, raw: body)
48
- when 403 then PermissionError.new(message, code: code, http_status: status, errors: field_errors, raw: body)
49
- when 404 then NotFoundError.new(message, code: code, http_status: status, errors: field_errors, raw: body)
50
- when 429 then RateLimitError.new(message, code: code, http_status: status, errors: field_errors, raw: body, retry_after: retry_after)
51
- when 400, 422 then InvalidRequestError.new(message, code: code, http_status: status, errors: field_errors, raw: body)
52
- else WajubError.new(message, code: code, http_status: status, errors: field_errors, raw: body)
56
+ when 401 then AuthenticationError.new(message, **details)
57
+ when 403 then PermissionError.new(message, **details)
58
+ when 404 then NotFoundError.new(message, **details)
59
+ when 429 then RateLimitError.new(message, **details, retry_after: retry_after)
60
+ when 400, 422 then InvalidRequestError.new(message, **details)
61
+ else WajubError.new(message, **details)
53
62
  end
54
63
  end
55
64
 
@@ -60,5 +69,13 @@ module Wajub
60
69
  value.is_a?(Array) ? value.first.to_s : value.to_s
61
70
  end
62
71
  end
72
+
73
+ def parse_all_field_errors(raw)
74
+ return nil unless raw.is_a?(Hash)
75
+
76
+ raw.transform_values do |value|
77
+ value.is_a?(Array) ? value.map(&:to_s) : [value.to_s]
78
+ end
79
+ end
63
80
  end
64
81
  end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require 'securerandom'
4
4
  require 'json'
5
+ require 'uri'
5
6
 
6
7
  module Wajub
7
8
  module HttpUtils
@@ -17,6 +18,22 @@ module Wajub
17
18
  API_URL
18
19
  end
19
20
 
21
+ # An id as one segment of a request path. The API reads an encoded "/" as
22
+ # a separator, an empty id leaves its segment out, and "." or ".." are dot
23
+ # segments that servers resolve: such an id would reach another route. No
24
+ # Wajub id takes these forms, so it is refused before anything is sent.
25
+ def path_segment(id)
26
+ raise ArgumentError, 'Wajub: an id is required (got nil)' if id.nil?
27
+
28
+ value = id.to_s
29
+ raise ArgumentError, "Wajub: an id must not contain \"/\" (got #{value.inspect})" if value.include?('/')
30
+ raise ArgumentError, "Wajub: #{value.inspect} is not a Wajub id" if ['', '.', '..'].include?(value)
31
+
32
+ # Form encoding writes a space as "+", which a path reads as a plus sign;
33
+ # it writes a "+" as %2B, so every "+" left is a space.
34
+ URI.encode_www_form_component(value).gsub('+', '%20')
35
+ end
36
+
20
37
  def create_idempotency_key(prefix = 'wajub')
21
38
  "#{prefix}-#{SecureRandom.uuid}"
22
39
  end
@@ -20,7 +20,7 @@ module Wajub
20
20
  end
21
21
 
22
22
  def retrieve(id)
23
- HttpUtils.pick_resource(get("/#{@path}/#{URI.encode_www_form_component(id)}"), @singular)
23
+ HttpUtils.pick_resource(get("/#{@path}/#{HttpUtils.path_segment(id)}"), @singular)
24
24
  end
25
25
 
26
26
  def list(params = nil)
@@ -28,11 +28,11 @@ module Wajub
28
28
  end
29
29
 
30
30
  def update(id, params, options = nil)
31
- HttpUtils.pick_resource(put("/#{@path}/#{URI.encode_www_form_component(id)}", params, options), @singular)
31
+ HttpUtils.pick_resource(put("/#{@path}/#{HttpUtils.path_segment(id)}", params, options), @singular)
32
32
  end
33
33
 
34
34
  def delete(id, options = nil)
35
- request('DELETE', "/#{@path}/#{URI.encode_www_form_component(id)}", options: options)
35
+ request('DELETE', "/#{@path}/#{HttpUtils.path_segment(id)}", options: options)
36
36
  end
37
37
  end
38
38
 
@@ -42,7 +42,7 @@ module Wajub
42
42
  end
43
43
 
44
44
  def retrieve(id)
45
- res = get("/payments/#{URI.encode_www_form_component(id)}")
45
+ res = get("/payments/#{HttpUtils.path_segment(id)}")
46
46
  to_payment_object('transaction' => HttpUtils.pick_resource(res, 'transaction'))
47
47
  end
48
48
 
@@ -51,22 +51,22 @@ module Wajub
51
51
  end
52
52
 
53
53
  def cancel(id, options = nil)
54
- res = delete("/payments/#{URI.encode_www_form_component(id)}", options)
54
+ res = delete("/payments/#{HttpUtils.path_segment(id)}", options)
55
55
  to_payment_object('transaction' => HttpUtils.pick_resource(res, 'transaction'))
56
56
  end
57
57
 
58
58
  def process(id, params, options = nil)
59
- res = post("/payments/#{URI.encode_www_form_component(id)}", params, options)
59
+ res = post("/payments/#{HttpUtils.path_segment(id)}", params, options)
60
60
  to_payment_object('transaction' => HttpUtils.pick_resource(res, 'transaction'))
61
61
  end
62
62
 
63
63
  def process_split(id, params, options = nil)
64
- res = post("/payments/#{URI.encode_www_form_component(id)}/splits", params, options)
64
+ res = post("/payments/#{HttpUtils.path_segment(id)}/splits", params, options)
65
65
  to_payment_object('transaction' => HttpUtils.pick_resource(res, 'transaction'))
66
66
  end
67
67
 
68
68
  def list_refunds(id, params = nil)
69
- list = HttpUtils.pick_list(get("/payments/#{URI.encode_www_form_component(id)}/refunds", params), 'refunds')
69
+ list = HttpUtils.pick_list(get("/payments/#{HttpUtils.path_segment(id)}/refunds", params), 'refunds')
70
70
  [list[:data], list[:meta]]
71
71
  end
72
72
 
@@ -116,11 +116,11 @@ module Wajub
116
116
  end
117
117
 
118
118
  def retrieve(id)
119
- HttpUtils.pick_resource(get("/events/#{URI.encode_www_form_component(id)}"), 'event')
119
+ HttpUtils.pick_resource(get("/events/#{HttpUtils.path_segment(id)}"), 'event')
120
120
  end
121
121
 
122
122
  def resend(id, options = nil)
123
- HttpUtils.pick_resource(post("/events/#{URI.encode_www_form_component(id)}/resend", nil, options), 'event')
123
+ HttpUtils.pick_resource(post("/events/#{HttpUtils.path_segment(id)}/resend", nil, options), 'event')
124
124
  end
125
125
  end
126
126
 
@@ -130,33 +130,33 @@ module Wajub
130
130
  end
131
131
 
132
132
  def block(id, params = nil, options = nil)
133
- HttpUtils.pick_resource(post("/customers/#{URI.encode_www_form_component(id)}/block", params, options), 'customer')
133
+ HttpUtils.pick_resource(post("/customers/#{HttpUtils.path_segment(id)}/block", params, options), 'customer')
134
134
  end
135
135
 
136
136
  def unblock(id, options = nil)
137
- HttpUtils.pick_resource(post("/customers/#{URI.encode_www_form_component(id)}/unblock", nil, options), 'customer')
137
+ HttpUtils.pick_resource(post("/customers/#{HttpUtils.path_segment(id)}/unblock", nil, options), 'customer')
138
138
  end
139
139
 
140
140
  def activate(id, options = nil)
141
- HttpUtils.pick_resource(post("/customers/#{URI.encode_www_form_component(id)}/activate", nil, options), 'customer')
141
+ HttpUtils.pick_resource(post("/customers/#{HttpUtils.path_segment(id)}/activate", nil, options), 'customer')
142
142
  end
143
143
 
144
144
  def deactivate(id, options = nil)
145
- HttpUtils.pick_resource(post("/customers/#{URI.encode_www_form_component(id)}/deactivate", nil, options), 'customer')
145
+ HttpUtils.pick_resource(post("/customers/#{HttpUtils.path_segment(id)}/deactivate", nil, options), 'customer')
146
146
  end
147
147
 
148
148
  def list_tax_ids(customer_id)
149
- list = HttpUtils.pick_list(get("/customers/#{URI.encode_www_form_component(customer_id)}/tax_ids"), 'tax_ids')
149
+ list = HttpUtils.pick_list(get("/customers/#{HttpUtils.path_segment(customer_id)}/tax_ids"), 'tax_ids')
150
150
  [list[:data], list[:meta]]
151
151
  end
152
152
 
153
153
  def create_tax_id(customer_id, params, options = nil)
154
- HttpUtils.pick_resource(post("/customers/#{URI.encode_www_form_component(customer_id)}/tax_ids", params, options), 'tax_id')
154
+ HttpUtils.pick_resource(post("/customers/#{HttpUtils.path_segment(customer_id)}/tax_ids", params, options), 'tax_id')
155
155
  end
156
156
 
157
157
  def delete_tax_id(customer_id, tax_id, options = nil)
158
158
  # Not `delete`: on a CrudResource that one takes an id and encodes it as a path segment.
159
- path = "/customers/#{URI.encode_www_form_component(customer_id)}/tax_ids/#{URI.encode_www_form_component(tax_id)}"
159
+ path = "/customers/#{HttpUtils.path_segment(customer_id)}/tax_ids/#{HttpUtils.path_segment(tax_id)}"
160
160
  request('DELETE', path, options: options)
161
161
  end
162
162
  end
@@ -167,7 +167,7 @@ module Wajub
167
167
  end
168
168
 
169
169
  def regenerate_token(id, options = nil)
170
- HttpUtils.pick_resource(post("/accounts/#{URI.encode_www_form_component(id)}/token", nil, options), 'account')
170
+ HttpUtils.pick_resource(post("/accounts/#{HttpUtils.path_segment(id)}/token", nil, options), 'account')
171
171
  end
172
172
  end
173
173
 
@@ -177,7 +177,7 @@ module Wajub
177
177
  end
178
178
 
179
179
  def rotate_secret(id, options = nil)
180
- HttpUtils.pick_resource(post("/webhooks/#{URI.encode_www_form_component(id)}/rotate-secret", nil, options), 'endpoint')
180
+ HttpUtils.pick_resource(post("/webhooks/#{HttpUtils.path_segment(id)}/rotate-secret", nil, options), 'endpoint')
181
181
  end
182
182
  end
183
183
 
@@ -186,16 +186,27 @@ module Wajub
186
186
  super(api_key, base_url, 'invoices', 'invoice', 'invoices', idempotency_key_prefix, transport: transport)
187
187
  end
188
188
 
189
- def send(id, options = nil)
190
- HttpUtils.pick_resource(post("/invoices/#{URI.encode_www_form_component(id)}/send", nil, options), 'invoice')
189
+ # Sends the invoice to its customer.
190
+ def send_invoice(id, options = nil)
191
+ HttpUtils.pick_resource(post("/invoices/#{HttpUtils.path_segment(id)}/send", nil, options), 'invoice')
192
+ end
193
+
194
+ # Kept for code that sends an invoice with send(id). Called with a Symbol,
195
+ # it is Object#send, so code that calls methods by name keeps working. A
196
+ # String is always an invoice id, even one that names a method, so an id
197
+ # taken from a request never calls a method.
198
+ def send(id_or_method, *args, **kwargs, &block)
199
+ return super if id_or_method.is_a?(Symbol)
200
+
201
+ send_invoice(id_or_method, *args, **kwargs)
191
202
  end
192
203
 
193
204
  def mark_paid(id, params = nil, options = nil)
194
- HttpUtils.pick_resource(post("/invoices/#{URI.encode_www_form_component(id)}/mark-paid", params, options), 'invoice')
205
+ HttpUtils.pick_resource(post("/invoices/#{HttpUtils.path_segment(id)}/mark-paid", params, options), 'invoice')
195
206
  end
196
207
 
197
208
  def cancel(id, options = nil)
198
- HttpUtils.pick_resource(post("/invoices/#{URI.encode_www_form_component(id)}/cancel", nil, options), 'invoice')
209
+ HttpUtils.pick_resource(post("/invoices/#{HttpUtils.path_segment(id)}/cancel", nil, options), 'invoice')
199
210
  end
200
211
  end
201
212
 
@@ -205,23 +216,23 @@ module Wajub
205
216
  end
206
217
 
207
218
  def retrieve(id)
208
- HttpUtils.pick_resource(get("/disputes/#{URI.encode_www_form_component(id)}"), 'dispute')
219
+ HttpUtils.pick_resource(get("/disputes/#{HttpUtils.path_segment(id)}"), 'dispute')
209
220
  end
210
221
 
211
222
  def submit_evidence(id, params, options = nil)
212
- HttpUtils.pick_resource(post("/disputes/#{URI.encode_www_form_component(id)}/submit-evidence", params, options), 'dispute')
223
+ HttpUtils.pick_resource(post("/disputes/#{HttpUtils.path_segment(id)}/submit-evidence", params, options), 'dispute')
213
224
  end
214
225
 
215
226
  def accept(id, options = nil)
216
- HttpUtils.pick_resource(post("/disputes/#{URI.encode_www_form_component(id)}/accept", nil, options), 'dispute')
227
+ HttpUtils.pick_resource(post("/disputes/#{HttpUtils.path_segment(id)}/accept", nil, options), 'dispute')
217
228
  end
218
229
 
219
230
  def close(id, options = nil)
220
- HttpUtils.pick_resource(post("/disputes/#{URI.encode_www_form_component(id)}/close", nil, options), 'dispute')
231
+ HttpUtils.pick_resource(post("/disputes/#{HttpUtils.path_segment(id)}/close", nil, options), 'dispute')
221
232
  end
222
233
 
223
234
  def send_message(id, params, options = nil)
224
- HttpUtils.pick_resource(post("/disputes/#{URI.encode_www_form_component(id)}/messages", params, options), 'dispute')
235
+ HttpUtils.pick_resource(post("/disputes/#{HttpUtils.path_segment(id)}/messages", params, options), 'dispute')
225
236
  end
226
237
  end
227
238
 
@@ -264,7 +275,7 @@ module Wajub
264
275
  end
265
276
 
266
277
  def retrieve_code(code)
267
- HttpUtils.pick_resource(get("/tax/codes/#{URI.encode_www_form_component(code)}"), 'tax_code', 'code')
278
+ HttpUtils.pick_resource(get("/tax/codes/#{HttpUtils.path_segment(code)}"), 'tax_code', 'code')
268
279
  end
269
280
 
270
281
  def list_registrations(params = nil)
@@ -276,15 +287,15 @@ module Wajub
276
287
  end
277
288
 
278
289
  def retrieve_registration(id)
279
- HttpUtils.pick_resource(get("/tax/registrations/#{URI.encode_www_form_component(id)}"), 'registration', 'tax_registration')
290
+ HttpUtils.pick_resource(get("/tax/registrations/#{HttpUtils.path_segment(id)}"), 'registration', 'tax_registration')
280
291
  end
281
292
 
282
293
  def update_registration(id, params, options = nil)
283
- HttpUtils.pick_resource(put("/tax/registrations/#{URI.encode_www_form_component(id)}", params, options), 'registration', 'tax_registration')
294
+ HttpUtils.pick_resource(put("/tax/registrations/#{HttpUtils.path_segment(id)}", params, options), 'registration', 'tax_registration')
284
295
  end
285
296
 
286
297
  def delete_registration(id, options = nil)
287
- request('DELETE', "/tax/registrations/#{URI.encode_www_form_component(id)}", options: options)
298
+ request('DELETE', "/tax/registrations/#{HttpUtils.path_segment(id)}", options: options)
288
299
  end
289
300
 
290
301
  def jurisdictions(params = nil)
@@ -326,16 +337,23 @@ module Wajub
326
337
  end
327
338
 
328
339
  def remove_from_blocklist(id, options = nil)
329
- request('DELETE', "/shield/blocklist/#{URI.encode_www_form_component(id)}", options: options)
340
+ request('DELETE', "/shield/blocklist/#{HttpUtils.path_segment(id)}", options: options)
330
341
  end
331
342
  end
332
343
 
344
+ # Deprecated: the API no longer offers these calls. To receive webhooks on
345
+ # your machine, forward them with the Wajub CLI's `wajub listen`. Each call
346
+ # warns when Ruby shows deprecation warnings (-W:deprecated).
333
347
  class ListenResource < BaseClient
334
348
  def config
349
+ warn('Wajub: listen.config is deprecated: the API no longer offers it. ' \
350
+ 'Forward webhooks with the Wajub CLI: wajub listen', uplevel: 1, category: :deprecated)
335
351
  HttpUtils.pick_resource(get('/listen/config'), 'config', 'listen')
336
352
  end
337
353
 
338
354
  def auth(params, options = nil)
355
+ warn('Wajub: listen.auth is deprecated: the API no longer offers it. ' \
356
+ 'Forward webhooks with the Wajub CLI: wajub listen', uplevel: 1, category: :deprecated)
339
357
  HttpUtils.pick_resource(post('/listen/auth', params, options), 'auth', 'listen')
340
358
  end
341
359
  end
data/lib/wajub/version.rb CHANGED
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Wajub
4
- VERSION = '1.3.0'
4
+ VERSION = '1.4.0'
5
5
  API_URL = 'https://api.wajub.com'
6
6
  end
@@ -17,6 +17,9 @@ module Wajub
17
17
 
18
18
  # A missing signature or timestamp header (nil, as request.headers returns
19
19
  # it) raises WebhookSignatureVerificationError, like a wrong one.
20
+ #
21
+ # +tolerance+ is the replay window in seconds. Anything but a positive
22
+ # number (0, a negative number, nil, a String) keeps the default of 300.
20
23
  def construct_event(payload, signature, timestamp, tolerance = DEFAULT_TOLERANCE)
21
24
  raise ArgumentError, 'Wajub: webhook_secret is required for construct_event' if @secret.empty?
22
25
  if signature.to_s.empty? || timestamp.to_s.empty?
@@ -34,10 +37,11 @@ module Wajub
34
37
  ts = Float(timestamp, exception: false)
35
38
  raise WebhookSignatureVerificationError, 'Invalid webhook timestamp.' unless ts&.finite?
36
39
 
40
+ window = replay_window(tolerance)
37
41
  drift = (Time.now.to_i - ts).abs
38
- if tolerance.positive? && drift > tolerance
42
+ if drift > window
39
43
  raise WebhookSignatureVerificationError,
40
- "Timestamp outside tolerance zone (#{drift.to_i}s drift, allowed #{tolerance}s)."
44
+ "Timestamp outside tolerance zone (#{drift.to_i}s drift, allowed #{window}s)."
41
45
  end
42
46
 
43
47
  event = JSON.parse(body)
@@ -45,5 +49,14 @@ module Wajub
45
49
 
46
50
  event
47
51
  end
52
+
53
+ private
54
+
55
+ # A tolerance of 0 or less used to switch the timestamp check off, which let
56
+ # a replayed delivery through.
57
+ def replay_window(tolerance)
58
+ valid = tolerance.is_a?(Numeric) && tolerance.real? && tolerance.finite? && tolerance.positive?
59
+ valid ? tolerance : DEFAULT_TOLERANCE
60
+ end
48
61
  end
49
62
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: wajub
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.3.0
4
+ version: 1.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Wajub
@@ -53,7 +53,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
53
53
  - !ruby/object:Gem::Version
54
54
  version: '0'
55
55
  requirements: []
56
- rubygems_version: 4.0.21
56
+ rubygems_version: 4.0.20
57
57
  specification_version: 4
58
58
  summary: Official Wajub Ruby SDK
59
59
  test_files: []