assinafy 2.2.0 → 2.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.
data/README.en.md CHANGED
@@ -5,40 +5,26 @@
5
5
  [![CI](https://github.com/assinafy/ruby-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/assinafy/ruby-sdk/actions/workflows/ci.yml)
6
6
  [![Gem Version](https://img.shields.io/gem/v/assinafy.svg)](https://rubygems.org/gems/assinafy)
7
7
 
8
- Ruby SDK for the [Assinafy API v1](https://api.assinafy.com.br/v1/docs).
8
+ Ruby 3.2+ SDK (prefer 4.0.10, 3.4.13 or 3.3.14) for the integration operations of the
9
+ [Assinafy API v1](https://api.assinafy.com.br/v1/docs): OAuth 2.1, documents, envelopes, contracts, signers,
10
+ assignments with every verification and notification method, embedded signing, scheduled sends, templates,
11
+ tags, fields and signed webhooks.
9
12
 
10
- Run this SDK on your server. Mobile and browser clients call your backend; keep API keys, OAuth client secrets,
11
- refresh tokens and signer access codes out of application bundles, logs and browser storage.
13
+ Run it on your server. Keep API keys, OAuth client secrets, refresh tokens and signer access codes out of mobile
14
+ and browser bundles, logs and repositories.
12
15
 
13
- The SDK exposes every Assinafy API v1 operation — including OAuth 2.1, two-factor authentication, webhook
14
- endpoints with native signatures, and the complete supported template lifecycle. The checked-in
15
- [`spec/api_coverage_spec.rb`](spec/api_coverage_spec.rb) validates that each route maps uniquely to a public SDK
16
- method.
16
+ - **Integration guide:** [docs/GUIDE.md](docs/GUIDE.md), with every step in detail and the call for each resource
17
+ - **API reference:** [docs/API_REFERENCE.md](docs/API_REFERENCE.md), with each operation mapped to its Ruby method,
18
+ authentication, parameters, request body, response and every schema
19
+ - **Type signatures:** [sig/assinafy.rbs](sig/assinafy.rbs)
17
20
 
18
- - **Source:** <https://github.com/assinafy/ruby-sdk>
19
- - **Issues:** <https://github.com/assinafy/ruby-sdk/issues>
20
- - **API docs:** <https://api.assinafy.com.br/v1/docs>
21
- - **Ruby SDK API reference:** [`docs/API_REFERENCE.md`](docs/API_REFERENCE.md)
22
-
23
- This guide follows an integration end to end — [install and configure](#installation-and-configuration),
24
- [authenticate](#authentication), [connect over OAuth](#oauth-21), then the
25
- [complete document workflow](#complete-document-workflow) — and ends with a
26
- [per-resource reference](#resource-reference).
27
-
28
- ## Installation and configuration
29
-
30
- Requirements: Ruby 3.2+ (maintained support: 3.3+; 3.2 is legacy/EOL compatibility), Bundler, and TLS 1.2 or
31
- newer (the SDK refuses TLS 1.0 and 1.1).
21
+ ## Installation
32
22
 
33
23
  ```ruby
34
24
  gem 'assinafy'
35
25
  ```
36
26
 
37
- ```bash
38
- bundle install
39
- ```
40
-
41
- From GitHub Packages (mirror), with a personal access token that has the `read:packages` scope:
27
+ From GitHub Packages, with a token that has `read:packages`:
42
28
 
43
29
  ```ruby
44
30
  source 'https://rubygems.pkg.github.com/assinafy' do
@@ -46,1150 +32,254 @@ source 'https://rubygems.pkg.github.com/assinafy' do
46
32
  end
47
33
  ```
48
34
 
49
- ```bash
50
- bundle config https://rubygems.pkg.github.com/assinafy USERNAME:TOKEN
51
- ```
52
-
53
- ### Environments
54
-
55
- | Environment | `base_url` | OAuth authorization server |
56
- | --- | --- | --- |
57
- | Production | `https://api.assinafy.com.br/v1` (default) | `https://auth.assinafy.com.br` |
58
- | Sandbox | `https://sandbox.assinafy.com.br/v1` | `https://auth-sandbox.assinafy.com.br` |
59
-
60
- The sandbox is free: use it to test an integration before production by changing `base_url` and, for OAuth, the
61
- authorization server. Never send sandbox API keys to production or the reverse. Webhook endpoints and two-factor
62
- authentication are available in production (`api.assinafy.com.br`).
63
-
64
- ### Configuration
35
+ ## Configuration and authentication
65
36
 
66
37
  ```ruby
67
- require 'logger'
38
+ require 'assinafy'
39
+
68
40
  client = Assinafy::Client.new(
69
- api_key: ENV.fetch('ASSINAFY_API_KEY'),
70
- account_id: ENV.fetch('ASSINAFY_ACCOUNT_ID'),
71
- base_url: ENV.fetch('ASSINAFY_BASE_URL', 'https://api.assinafy.com.br/v1'),
72
- webhook_secret: ENV['ASSINAFY_WEBHOOK_SECRET'], # the endpoint's whsec_... secret
73
- timeout: 30,
74
- logger: Logger.new($stdout)
41
+ api_key: ENV.fetch('ASSINAFY_API_KEY'), # or token: for an OAuth access token
42
+ account_id: ENV.fetch('ASSINAFY_ACCOUNT_ID'), # default workspace; methods accept an override
43
+ base_url: 'https://api.assinafy.com.br/v1', # default
44
+ webhook_secret: ENV['ASSINAFY_WEBHOOK_SECRET'],
45
+ timeout: 60
75
46
  )
76
47
  ```
77
48
 
78
- - `base_url:` must be an absolute `http`/`https` URL. Anything else — a scheme-less host, a relative path, or
79
- another scheme — raises `Assinafy::ValidationError` instead of attaching your credentials to it. A trailing
80
- slash is stripped. `Configuration#base_url=` and `#timeout=` validate the same way as the constructor.
81
- - Account-scoped methods accept a per-call account override for multi-workspace tenants.
82
- - `logger:` receives SDK lifecycle messages, never request bodies or credentials.
83
- - Every request sends `User-Agent: Assinafy-Ruby-SDK/v<Assinafy::VERSION>`.
84
- - `Client.from_config(hash)` accepts string- or symbol-keyed hashes (e.g. parsed YAML).
85
-
86
- ## Authentication
87
-
88
49
  | Credential | Who acts | Use for |
89
50
  | --- | --- | --- |
90
- | **API key** (`api_key:`) | the workspace | back-end integrations. Permanent. Sent as `X-Api-Key`. |
91
- | **Session token** (`token:`) | the logged-in user | after `client.auth.login`. A JWT that expires in about an hour. |
92
- | **OAuth 2.1** (`token:`) | an app, **on behalf of** a user | marketplace apps, third-party integrations, AI assistants. See [OAuth 2.1](#oauth-21). |
93
-
94
- Configure exactly one credential per client; if both are supplied, the SDK sends only `X-Api-Key`. A client with
95
- no credentials serves login, OAuth, and public or signer endpoints — the SDK strips `X-Api-Key`/`Authorization`
96
- from those calls regardless.
97
-
98
- ### Login, with the two-factor challenge
99
-
100
- ```ruby
101
- public_client = Assinafy::Client.new
102
- session = public_client.auth.login(email: 'user@example.com', password: ENV.fetch('ASSINAFY_PASSWORD'))
103
-
104
- if session['mfa_token']
105
- session = public_client.auth.verify_mfa(
106
- mfa_token: session['mfa_token'],
107
- code: '123456' # or a recovery code such as "ABCD-EFGH-JKMN"
108
- )
109
- end
110
-
111
- user_client = Assinafy::Client.new(
112
- token: session.fetch('access_token'),
113
- account_id: session.fetch('accounts').first.fetch('id')
114
- )
115
- ```
116
-
117
- When the user has two-factor authentication enabled, `login` answers with an `mfa_token` challenge instead of an
118
- access token. `verify_mfa` is sent without workspace credentials. The challenge is single-use and expires 5 minutes
119
- after login; a wrong code answers `400`, and an expired, used, or over-attempted challenge answers `401` — log in
120
- again. `social_login` returns the same shape.
121
-
122
- ### Managing two-factor authentication
123
-
124
- ```ruby
125
- enrollment = user_client.auth.start_totp_enrollment(label: 'My phone')
126
- enrollment['provisioning_uri'] # => "otpauth://totp/...": render as a QR code
127
- enrollment['secret'] # returned only by this call
128
-
129
- codes = user_client.auth.confirm_totp_enrollment(method_id: enrollment.fetch('id'), code: '123456')
130
- codes['recovery_codes'] # => ["ABCD-EFGH-JKMN", ...] — shown only once
131
-
132
- user_client.auth.mfa_methods
133
- # => { 'methods' => [{ 'id' => 'mfa-method-id', 'type' => 'Totp', 'label' => 'My phone', ... }],
134
- # 'recovery_codes_remaining' => 10 }
135
-
136
- user_client.auth.regenerate_recovery_codes(password: ENV.fetch('ASSINAFY_PASSWORD'))
137
- user_client.auth.delete_mfa_method('mfa-method-id', code: '123456') # => { 'is_mfa_enabled' => false }
138
- ```
51
+ | `api_key:` (`X-Api-Key`) | the workspace | back-end integrations; generate the key in the Assinafy app |
52
+ | `token:` from OAuth 2.1 | an app on behalf of a user | marketplace apps; register the OAuth client in the Assinafy app |
139
53
 
140
- - Two-factor authentication stays off until `confirm_totp_enrollment` succeeds.
141
- - Confirming a new authenticator while one is already confirmed **replaces** it and requires re-authentication
142
- with `password:` or `reauth_code:` (a code from the current device, or a recovery code).
143
- - `regenerate_recovery_codes` and `delete_mfa_method` require `password:` or `code:`; with neither, the SDK raises
144
- `ValidationError` before sending. A recovery code used as proof is consumed. Removing the last method also
145
- discards the recovery codes.
54
+ User login, passwords, two-factor setup and API-key management stay in the Assinafy app; the SDK does not wrap
55
+ them.
146
56
 
147
- ### API keys and passwords
57
+ Configure one credential per client; when both are set only `X-Api-Key` is sent. Public and signer endpoints,
58
+ OAuth token and revocation requests, and discovery documents strip workspace credentials automatically. `base_url` must be an absolute `http(s)` URL, connections
59
+ require TLS 1.2+, and every request sends `User-Agent: Assinafy-Ruby-SDK/v<version>`. Keep `timeout` above 30
60
+ seconds: signed page renders can wait 30 seconds before answering.
148
61
 
149
- ```ruby
150
- client.auth.create_api_key(password: 'secret') # shown once; replaces the previous key
151
- client.auth.get_api_key # masked
152
- client.auth.delete_api_key
153
- client.auth.social_login(provider: 'google', token: 'id-token', has_accepted_terms: true)
154
- client.auth.link_social_login(provider: 'google', token: 'id-token')
155
- client.auth.change_password(email: 'user@example.com', password: 'old', new_password: 'new')
156
- client.auth.request_password_reset(email: 'user@example.com')
157
- client.auth.reset_password(email: 'user@example.com', new_password: 'new', token: 'reset-token')
158
- ```
159
-
160
- ## OAuth 2.1
161
-
162
- Use OAuth when an application acts **on behalf of a user**, with that user's permission. Unlike an API key, the
163
- token is scoped to one workspace and carries only the scopes the user approved. Third-party OAuth tokens cannot
164
- reach billing, account lifecycle, credential management, webhook-secret reads, embed-session creation,
165
- biometric review images/decisions, or admin surfaces, whatever scopes they hold.
62
+ ## OAuth 2.1 for marketplace apps
166
63
 
167
- The flow is authorization-code with **mandatory PKCE**; the authorization server accepts `S256` only.
168
-
169
- | Scope | Grants |
170
- | --- | --- |
171
- | `documents:read` | Read documents, pages, tags, signers, assignments, activity, webhook deliveries |
172
- | `documents:write` | Create, update, delete documents and manage their signers and assignments |
173
- | `templates:read` | Read templates, pages, roles, fields, tags |
174
- | `templates:write` | Create, update, delete templates |
175
- | `account:read` | Read the workspace profile, theme, logo, webhook endpoints |
176
- | `webhooks:write` | Create, change, deactivate, and delete the workspace's webhook endpoints |
177
- | `openid` | Identify the user (`sub` claim) and enable `/oauth/userinfo` |
178
- | `profile` | Include the user's name in the claims |
179
- | `email` | Include the user's email and verification status in the claims |
180
- | `offline_access` | Be issued a refresh token (never echoed in the returned `scope`) |
181
-
182
- **1. Register a callback and redirect the user.** Register an HTTPS callback URL in the Assinafy application.
183
- For each authorization attempt, store the verifier, the state, and the expected issuer:
64
+ Authorization code with mandatory PKCE `S256`. Register an HTTPS callback in the Assinafy app, then for each
65
+ attempt store the verifier, the state and the expected issuer on your server:
184
66
 
185
67
  ```ruby
186
68
  verifier = Assinafy::OAuth.generate_code_verifier
187
69
  state = Assinafy::OAuth.generate_state
188
-
189
- session[:assinafy_code_verifier] = verifier
190
- session[:assinafy_state] = state
191
- session[:assinafy_issuer] = Assinafy::OAuth::AUTHORIZATION_SERVER # issuer of the server this attempt uses
70
+ session.merge!(code_verifier: verifier, state: state, issuer: Assinafy::OAuth::AUTHORIZATION_SERVER)
192
71
 
193
72
  redirect_to Assinafy::OAuth.authorization_url(
194
73
  client_id: ENV.fetch('ASSINAFY_CLIENT_ID'),
195
74
  redirect_uri: 'https://app.example.com/oauth/callback',
196
75
  code_verifier: verifier,
197
76
  state: state,
198
- scope: %w[documents:read documents:write openid profile email offline_access]
77
+ scope: %w[openid profile email documents:read documents:write offline_access]
199
78
  )
200
79
  ```
201
80
 
202
- The `code_challenge` is derived from the verifier; the verifier itself never appears in the URL.
203
- `Assinafy::OAuth::AUTHORIZATION_SERVER` is the production issuer. For the sandbox, pass
204
- `authorization_endpoint: 'https://auth-sandbox.assinafy.com.br/oauth/authorize'` and store
205
- `https://auth-sandbox.assinafy.com.br` instead.
206
-
207
- **2. Validate the callback and exchange the code.** Check `state` and `iss` against the values stored for this
208
- attempt before anything else, including on an `error=` return — that is the CSRF check, and it rejects responses
209
- that are not yours. The code is single-use and expires 60 seconds after approval: exchange it at once, with the
210
- same `redirect_uri`, and never retry.
81
+ On the callback, compare `state` and `iss` with the stored values before reading `code` or `error`, then exchange
82
+ the single-use code at once (it expires 60 seconds after consent) and never retry it:
211
83
 
212
84
  ```ruby
213
- expected_state = session.delete(:assinafy_state)
214
- expected_issuer = session.delete(:assinafy_issuer)
215
- unless expected_state.is_a?(String) && !expected_state.empty? &&
216
- expected_issuer.is_a?(String) && !expected_issuer.empty? &&
217
- params[:state] == expected_state && params[:iss] == expected_issuer
218
- raise 'authorization response is not ours'
219
- end
220
- raise "authorization not granted: #{params[:error]}" if params[:error] # access_denied, invalid_scope, ...
85
+ raise 'not our authorization' unless params[:state] == session.delete(:state) &&
86
+ params[:iss] == session.delete(:issuer)
221
87
 
222
88
  tokens = Assinafy::Client.new.oauth.exchange_code(
223
89
  code: params.fetch(:code),
224
90
  client_id: ENV.fetch('ASSINAFY_CLIENT_ID'),
225
- code_verifier: session.delete(:assinafy_code_verifier),
91
+ code_verifier: session.delete(:code_verifier),
226
92
  redirect_uri: 'https://app.example.com/oauth/callback'
227
93
  )
228
- # => { 'access_token' => ..., 'token_type' => 'Bearer', 'expires_in' => 3600,
229
- # 'refresh_token' => ..., 'scope' => 'documents:read documents:write openid profile email' }
230
- ```
231
-
232
- The SDK checks the `code_verifier` grammar locally, because the server reports a malformed verifier as
233
- `invalid_grant` — indistinguishable from an expired code.
234
-
235
- **3. Persist the connection and act as the user.** The token works only in the workspace the user picked.
236
-
237
- ```ruby
238
- access_token = tokens.fetch('access_token')
239
- workspace_id = Assinafy::Client.new(token: access_token).accounts.list[:data].first.fetch('id')
240
-
241
- connection = Connection.create!(
242
- workspace_id: workspace_id,
243
- scope: tokens.fetch('scope'),
244
- access_token: access_token, # store encrypted
245
- refresh_token: tokens['refresh_token'], # store encrypted
246
- expires_at: Time.now + tokens.fetch('expires_in')
247
- )
248
-
249
- user_client = Assinafy::Client.new(token: connection.access_token, account_id: connection.workspace_id)
250
- user_client.documents.list
251
- user_client.oauth.userinfo # => { 'sub' => ..., 'name' => ..., 'email' => ... } (openid scope)
94
+ user_client = Assinafy::Client.new(token: tokens.fetch('access_token'), account_id: 'workspace-id')
252
95
  ```
253
96
 
254
- **4. Refresh with rotation, one at a time per connection.** Every refresh returns a **new** refresh token, valid
255
- for another 30 days, and retires the old one, so a connection only expires after 30 days without a refresh.
256
- Reusing a retired refresh token ends the whole connection, so refresh under a per-connection lock and store the
257
- new tokens atomically before using them:
97
+ Persist the workspace, granted scopes, expiry and encrypted tokens. Each refresh returns a new refresh token valid
98
+ for 30 days and retires the old one, so refresh one at a time per connection, inside a lock, and store both new
99
+ tokens atomically. The SDK sends token and revoke requests exactly once; never add retry middleware. On
100
+ disconnect, revoke the latest refresh token:
258
101
 
259
102
  ```ruby
260
- connection.with_lock do # row lock: one refresh at a time per connection
261
- next if connection.expires_at > Time.now + 60 # another worker already refreshed
262
-
263
- tokens = Assinafy::Client.new.oauth.refresh(
264
- refresh_token: connection.refresh_token,
265
- client_id: ENV.fetch('ASSINAFY_CLIENT_ID')
266
- )
267
-
268
- connection.update!(
269
- refresh_token: tokens.fetch('refresh_token'),
270
- access_token: tokens.fetch('access_token'),
271
- expires_at: Time.now + tokens.fetch('expires_in')
272
- )
103
+ connection.with_lock do
104
+ tokens = Assinafy::Client.new.oauth.refresh(refresh_token: connection.refresh_token,
105
+ client_id: ENV.fetch('ASSINAFY_CLIENT_ID'))
106
+ connection.update!(access_token: tokens.fetch('access_token'), refresh_token: tokens.fetch('refresh_token'),
107
+ expires_at: Time.now + tokens.fetch('expires_in'))
273
108
  end
274
- user_client = Assinafy::Client.new(token: connection.access_token, account_id: connection.workspace_id)
275
- ```
276
-
277
- > The SDK does **not** refresh automatically and sends each token request once — never add retry middleware to
278
- > the connection. `refresh` raises `Assinafy::Error` rather than return a success without a new refresh token;
279
- > handle it like `invalid_grant`.
280
- >
281
- > If a refresh fails without a clear answer — a timeout, a reset connection, a `5xx` — the server may have rotated
282
- > the token without the response reaching you. Re-read the stored refresh token: if it is still the one you sent,
283
- > **never send it again**; ask the user to connect again. Carry on only if another worker has since stored a
284
- > different one. Only a failure that provably happened before the request was sent — DNS resolution, a refused
285
- > connection, a failed TLS handshake — is safe to retry. On an API `401`, refresh once; if that fails, or on
286
- > `invalid_grant`, ask the user to connect again.
287
-
288
- A refresh token exists only when `offline_access` was requested *and* consented.
289
-
290
- **5. Revoke on disconnect.** Revoke the refresh token in storage **now** — the latest one — then delete the stored
291
- tokens:
292
-
293
- ```ruby
294
- Assinafy::Client.new.oauth.revoke(
295
- token: connection.reload.refresh_token,
296
- client_id: ENV.fetch('ASSINAFY_CLIENT_ID'),
297
- token_type_hint: 'refresh_token'
298
- )
299
- connection.destroy!
300
- ```
301
-
302
- Revoking a refresh token also invalidates the access tokens issued from it. Every revoke outcome returns `200` —
303
- including an unknown, already-revoked, or rotated token — so revoking a stale copy can look successful while the
304
- connection stays active.
305
-
306
- **Discovery**, instead of hardcoding endpoints:
307
-
308
- ```ruby
309
- client.oauth.protected_resource_metadata['authorization_servers']
310
- # => ["https://auth.assinafy.com.br"]
311
-
312
- client.oauth.authorization_server_metadata['code_challenge_methods_supported']
313
- # => ["S256"]
314
- ```
315
-
316
- `authorization_server_metadata` reaches a different host, so — like `/oauth/token` and `/oauth/revoke` — the SDK
317
- sends it with no workspace credentials attached. An override URL must be an absolute HTTPS URL; anything else
318
- raises `ValidationError`.
319
-
320
- **Internal service clients.** The advertised RFC 8693 token-exchange grant is restricted to
321
- Assinafy-provisioned confidential service clients. Marketplace apps use PKCE authorization code
322
- and refresh. `client.oauth.token` accepts token exchange with `client_secret`, `subject_token`,
323
- `subject_token_type`, and `resource`; it issues no refresh token.
324
109
 
325
- **Errors.** OAuth routes answer with the flat RFC 6749 object rather than this API's envelope, so the SDK raises
326
- `Assinafy::OAuthError` (a subclass of `Assinafy::ApiError`):
327
-
328
- ```ruby
329
- rescue Assinafy::OAuthError => e
330
- e.error # => "invalid_grant"
331
- e.error_description # => "The authorization code is invalid or has expired."
332
- e.context[:www_authenticate] # on a 403, names the missing scope
110
+ Assinafy::Client.new.oauth.revoke(token: connection.refresh_token, client_id: ENV.fetch('ASSINAFY_CLIENT_ID'),
111
+ token_type_hint: 'refresh_token')
333
112
  ```
334
113
 
335
- Any resource, not only these routes, puts that challenge in `context[:www_authenticate]`. Treat it as a prompt to
336
- reconnect with that scope added, not as a retry; a `403` without it means another workspace, the user's role, or
337
- an area OAuth tokens never reach.
338
-
339
- ## Complete document workflow
340
-
341
- Every call below returns the SDK value after response-envelope handling. Use the
342
- [API operation table](docs/API_REFERENCE.md#api-operations) for each method's exact HTTP authentication,
343
- parameters, request body, and success wire response.
344
-
345
- ### 1. Upload a document and wait for its metadata
346
-
347
- ```ruby
348
- document = client.documents.upload({ file_path: './customer-agreement.pdf' })
349
- document['name'] # => "customer-agreement.pdf"
350
-
351
- document = client.documents.wait_until_ready(
352
- document.fetch('id'),
353
- max_wait_seconds: 60,
354
- poll_interval_seconds: 2
355
- )
356
- # => Document with a ready status and populated pages
357
- ```
114
+ `offline_access` grants the refresh token but never appears in the returned `scope`. `oauth.userinfo`,
115
+ `protected_resource_metadata` and `authorization_server_metadata` complete the flow; a `403` names the missing
116
+ scope in `error.context[:www_authenticate]`. OAuth failures raise `Assinafy::OAuthError` with `error` and
117
+ `error_description`. See the [guide](docs/GUIDE.md#oauth-21) for scopes, failure handling and token exchange.
358
118
 
359
- The document is named after the uploaded file; rename it with `client.documents.rename(id, 'New name')`. For
360
- in-memory data, pass `{ buffer: pdf_bytes, file_name: 'contract.pdf' }`. PDF only, at most 25 MB: the SDK checks
361
- the extension, size, and `%PDF-` header before sending. `wait_until_ready` raises `Assinafy::ValidationError` for
362
- invalid interval values and `Assinafy::Error` for a failed terminal status or a timeout.
119
+ ## Complete signing flow
363
120
 
364
- **Or select a template.** A template upload initially contains an `Editor` role. Configure at least one `Signer`
365
- role and its fields in the Assinafy application before generating a document. Template uploads have the same
366
- 25 MB limit as documents.
121
+ 1. Upload a PDF, DOC, DOCX or ODT (up to 25 MB) and wait for its metadata, or pick a configured template.
122
+ 2. Create or reuse signers; store `government_id` for certificate or biometric verification.
123
+ 3. Estimate the cost, then create a `virtual` or `collect` assignment, an envelope or a scheduled send.
124
+ 4. The signer accepts the terms, verifies their identity, and signs or declines.
125
+ 5. Follow webhooks or activities, download the signed artifact and verify it.
126
+ 6. Track contract terms when the plan includes them; cancel or delete only what your app owns.
367
127
 
368
128
  ```ruby
369
- template = client.templates.get('template-id')
370
- ```
371
-
372
- ### 2. Create or reuse signers
129
+ document = client.documents.upload({ file_path: './contract.pdf' })
130
+ document = client.documents.wait_until_ready(document.fetch('id'))
373
131
 
374
- ```ruby
375
132
  signer = client.signers.find_by_email('signer@example.com') ||
376
133
  client.signers.create(full_name: 'Example Signer', email: 'signer@example.com')
377
134
 
378
- # A DigitalCertificate signer needs a CPF or CNPJ in government_id — set it at creation:
379
- cert_signer = client.signers.create(
380
- full_name: 'Certificate Signer',
381
- email: 'cert-signer@example.com',
382
- government_id: ENV.fetch('ASSINAFY_SIGNER_GOVERNMENT_ID')
383
- )
384
- # ...or later: client.signers.update(signer['id'], government_id: '...')
385
- ```
386
-
387
- ### 3. Choose verification and notification methods
388
-
389
- Each assignment signer has a **verification method** (how they prove identity before signing) and a
390
- **notification method** (how they receive the invitation). The two are **coupled**: send one, both, or neither —
391
- the missing side is inferred from the other, and when both are omitted both default to `Email`.
392
-
393
- | Verification | How it works | Allowed notification | Cost per signer |
394
- | --- | --- | --- | --- |
395
- | `Email` *(default)* | One-time code (OTP) by email before signing | `Email` | 0 credits |
396
- | `Whatsapp` | One-time code (OTP) over WhatsApp; needs `whatsapp_phone_number` and a paid plan | `Whatsapp` | 0.45 credits (the WhatsApp notification) |
397
- | `DigitalCertificate` | Signs with their own ICP-Brasil certificate (A1/A3), producing a qualified PAdES signature | `Email` **or** `Whatsapp` | 0.5 credits + its notification (0 or 0.45) |
398
- | `IdDocumentFaceMatchBasic` | Government ID photos, a photo holding the ID and liveness; requires its account feature and a valid CPF in `government_id` | `Email` **or** `Whatsapp` | Per-signer fee + notification; request an estimate |
399
-
400
- - Send exactly one channel in `notification_methods` (a one-element array).
401
- - The certificate charge appears in the cost breakdown under the code `SignatureDigitalCertificate`. Resending a
402
- notification charges the notification again.
403
- - `DigitalCertificate` needs the Digital Certificate account feature (Standard and Pro plans), a CPF or CNPJ in the
404
- signer's `government_id`, a `method: 'virtual'` assignment, and the signer alone in its signing step. A collect
405
- assignment, including one inferred from a template with positioned signer fields, cannot use certificate
406
- signing. Direct assignment creation and estimation reject it with `ValidationError` code
407
- `digital_certificate_requires_virtual`. A CPF requires that person's certificate (an e-CPF, or an e-CNPJ naming
408
- them as legal representative); a CNPJ requires an e-CNPJ for that company, from any of its representatives.
409
- - `AssignmentResource::VERIFICATION_METHODS` and `::NOTIFICATION_METHODS` publish the enums. `build_payload`
410
- validates values, pairings, and `step` locally, so a typo fails before the request is sent.
411
-
412
- ### 4. Estimate the cost
413
-
414
- ```ruby
415
- estimate = client.assignments.estimate_cost(
416
- document.fetch('id'),
417
- signers: [
418
- { verification_method: 'Email' },
419
- { verification_method: 'DigitalCertificate', notification_methods: ['Whatsapp'] }
420
- ]
421
- )
422
- estimate['total_credits'] # => 0.95
423
- estimate['breakdown'] # [{ 'code' => ..., 'quantity' => ..., 'unit_cost' => ..., 'cost' => ... }]
424
- estimate['has_sufficient_resources'] # => true
425
- ```
426
-
427
- Estimates accept signers described by method alone, without an `id`.
428
-
429
- ### 5. Create the assignment
430
-
431
- ```ruby
432
- assignment = client.assignments.create(
433
- document.fetch('id'),
434
- method: 'virtual',
435
- signers: [
436
- { id: signer.fetch('id'), verification_method: 'Email', notification_methods: ['Email'], step: 1 },
437
- { id: cert_signer.fetch('id'), verification_method: 'DigitalCertificate', notification_methods: ['Email'], step: 2 }
438
- ],
439
- message: 'Please review and sign.',
440
- expires_at: '2099-12-31T23:59:00Z'
441
- )
442
- assignment['signing_urls'] # => [{ 'signer_id' => 'signer-id', 'url' => 'https://.../sign/...' }, ...]
443
- ```
444
-
445
- `virtual` has no positioned fields and is required for `DigitalCertificate`; `collect` adds `entries` of
446
- positioned fields (see [Assignments](#assignments)). Both require a non-empty `signers` array. Steps are
447
- all-or-none, positive, and contiguous from 1; equal steps sign in parallel, and each step is notified when the
448
- previous one finishes. A certificate signer is alone in its step. Deadlines are zoned ISO 8601 and at least one
449
- hour ahead.
450
-
451
- For a template, bind one distinct signer to each role; processing creates the document's assignment:
452
-
453
- ```ruby
454
- role_signer = {
455
- role_id: template.fetch('roles').find { |role| role['assignment_type'] == 'Signer' }.fetch('id'),
456
- id: signer.fetch('id'),
457
- verification_method: 'Email',
458
- notification_methods: ['Email']
135
+ request = {
136
+ method: 'virtual',
137
+ signers: [{ id: signer.fetch('id'), verification_method: 'Email', notification_methods: ['Email'] }],
138
+ message: 'Please review and sign.',
139
+ expires_at: (Time.now + 7 * 86_400).utc.iso8601,
140
+ max_total_credits: 2
459
141
  }
460
142
 
461
- client.documents.estimate_cost_from_template(template.fetch('id'), [role_signer])
462
- template_document = client.documents.create_from_template(
463
- template.fetch('id'), [role_signer],
464
- name: 'customer-agreement.pdf', message: 'Please review and sign.',
465
- idempotency_key: 'template-request-id'
466
- )
467
- # Initial response: status "uploaded", assignment nil; processing creates the assignment afterward.
468
- # Follow document status/webhooks until pending_signature or failed.
469
- # wait_until_ready waits for metadata and can return before the template assignment exists.
470
- ```
471
-
472
- Template creation also accepts `email` and `name` for a role instead of an existing signer `id`; the server reuses
473
- or creates the signer. Keep the same `idempotency_key` after a lost response to avoid duplicate documents and
474
- charges. `max_total_credits` can cap creation costs; a higher actual price returns `409` with
475
- `error_code == 'CreditCeilingExceeded'`, creating and charging nothing.
476
-
477
- **Shortcut.** `Client#upload_and_request_signatures` bundles upload, waiting, signer creation (including
478
- `government_id`), and a virtual assignment, validating the whole payload before anything is uploaded:
479
-
480
- ```ruby
481
- result = client.upload_and_request_signatures(
482
- source: { file_path: './contract.pdf' },
483
- signers: [{ full_name: 'Alice Silva', email: 'alice@example.com' }],
484
- message: 'Please sign.',
485
- expires_at: '2099-12-31T23:59:00Z'
486
- )
487
- result[:document]['id'] # => "document-id"
488
- result[:signer_ids] # => ["signer-id"]
489
- ```
490
-
491
- It is not transactional: on a later failure, `e.context[:document]` and `e.context[:signer_ids]` list what was
492
- created so you can clean up.
493
-
494
- ### 6. The signer experience
495
-
496
- The signer receives an access link through the notification channel. Signer-facing calls use
497
- `signer-access-code` as a query parameter, with workspace credentials removed. The code remains usable during
498
- signing and closes 30 minutes after that signer is done; an envelope code closes after all their documents are
499
- done. After closure, document reads return only signer status, theme/logo and certified-copy delivery remain
500
- available, and other signer calls return `410`.
501
-
502
- ```ruby
503
- signing = Assinafy::Client.new(base_url: ENV.fetch('ASSINAFY_BASE_URL'))
504
- access_code = ENV.fetch('ASSINAFY_SIGNER_ACCESS_CODE')
505
-
506
- signer_data = signing.signers.self_data(signer_access_code: access_code)
507
- signing.signers.accept_terms(signer_access_code: access_code) unless signer_data['has_accepted_terms']
508
-
509
- signing_document = signing.assignments.signer_document(signer_access_code: access_code, has_accepted_terms: true)
510
- signing.signers.confirm_data(
511
- signing_document.fetch('id'), { email: 'signer@example.com', has_accepted_terms: true },
512
- signer_access_code: access_code
513
- )
514
- signing.signers.verify_email( # the OTP from email or WhatsApp
515
- verification_code: ENV.fetch('ASSINAFY_VERIFICATION_CODE'),
516
- signer_access_code: access_code
517
- )
518
- signing.signers.upload_signature(File.binread('signature.png'), signer_access_code: access_code, type: 'signature')
519
-
520
- signing.signer_documents.sign_multiple([signing_document.fetch('id')], signer_access_code: access_code)
521
- ```
522
-
523
- That signs a virtual assignment. For a collect assignment, submit each positioned item through
524
- `assignments.sign`; the SDK maps the snake_case item keys to the API's camelCase request keys:
525
-
526
- ```ruby
527
- collect_items = signing_document.fetch('assignment').fetch('items').map do |item|
528
- { item_id: item.fetch('id'), field_id: item.dig('field', 'id'), page_id: item.dig('page', 'id'), value: 'Accepted' }
529
- end
530
-
531
- signing.assignments.sign(
532
- signing_document.fetch('id'), signing_document.dig('assignment', 'id'), collect_items,
533
- signer_access_code: access_code
534
- )
535
-
536
- # To decline instead:
537
- signing.assignments.decline(
538
- signing_document.fetch('id'), signing_document.dig('assignment', 'id'),
539
- decline_reason: 'Terms differ from the proposal', signer_access_code: access_code
540
- )
143
+ client.assignments.estimate_cost(document.fetch('id'), request) # => { 'total_credits' => 0.0, ... }
144
+ assignment = client.assignments.create(document.fetch('id'), request)
145
+ assignment['signing_urls'] # => [{ 'signer_id' => '...', 'url' => 'https://app.assinafy.com.br/sign/...' }]
541
146
  ```
542
147
 
543
- **Biometric signers** use `verification_method: 'IdDocumentFaceMatchBasic'` with exactly one Email or Whatsapp
544
- notification in virtual/collect assignments or template generation. Store a valid CPF in the signer's
545
- `government_id` first and call `estimate_cost` or `estimate_cost_from_template` for the current price.
546
- The OTP example above applies to Email/Whatsapp. For biometrics, read the verification state and collect explicit
547
- biometric-processing consent before starting:
548
-
549
- ```ruby
550
- state = signing.signers.identity_verification(signer_access_code: access_code)
551
- # => { 'can_start' => true, 'status' => nil, 'url' => nil, 'expires_at' => nil, 'completed_at' => nil }
148
+ `client.upload_and_request_signatures(source:, signers:, ...)` runs upload, signer creation and the assignment
149
+ in one call; it validates the whole request, including each signer's methods, before uploading anything, and
150
+ leaves `document` and `signer_ids` in `error.context` if a later step fails.
552
151
 
553
- # After the signer explicitly consents to biometric processing:
554
- session = signing.signers.start_identity_verification(consent: true, signer_access_code: access_code)
555
- # => { 'id' => 'verification-id', 'url' => 'https://verify.assinafy.com.br/c/session#t=token-placeholder',
556
- # 'expires_at' => '2026-10-16T13:00:00Z' }
557
- ```
152
+ ### Verification and notification methods
558
153
 
559
- Open the capture URL unchanged, including its `#t=` fragment. It is a bearer link: keep it out of logs and browser
560
- storage. For an existing Pending session, use the URL from `identity_verification`. `can_start` is true only
561
- before any session or after Expired; restarting an Expired session costs nothing extra. Declined or Abandoned
562
- requires a new document and assignment.
563
-
564
- InReview lets the signer view, confirm data and sign while account review holds certification. After all signers
565
- sign, the document can be `pending_identity_review`. The account reviewer uses an API key or user session:
566
-
567
- ```ruby
568
- review = client.assignments.identity_review(document.fetch('id'), assignment.fetch('id'), signer.fetch('id'))
569
- # => SignerIdentityReview: status, reason_codes, evidence_available, expected, document, matches,
570
- # checks, images, ruleset_version, evidence_sha256 and decision metadata
571
- image = client.assignments.identity_review_image(document.fetch('id'), assignment.fetch('id'), signer.fetch('id'), 'face')
572
- # => JPEG, PNG or PDF bytes, depending on the name listed in review['images']; do not cache
573
-
574
- # After the reviewer checks the evidence:
575
- client.assignments.decide_identity_review(
576
- document.fetch('id'), assignment.fetch('id'), signer.fetch('id'), decision: 'Approved', note: 'Identity checked'
577
- )
578
- ```
579
-
580
- `decision: 'Rejected'` cancels the document and notifies signers and copy receivers. The optional note accepts at
581
- most 2000 characters, goes to activities and the provider, and is never shown to the signer. Images exist only
582
- during InReview. Observe signer_identity_review_required, signer_identity_review_approved,
583
- signer_identity_review_rejected, signer_identity_verified and signer_identity_verification_failed events.
584
- Third-party OAuth apps can read the review summary with `documents:read`; they cannot fetch evidence images or
585
- submit the human review decision. For envelopes, one biometric check covers the signer's documents; rejection
586
- cancels the whole envelope and notifies each recipient once.
587
-
588
- **A1/A3 certificate signers** complete their signature in Assinafy's hosted signing flow, opened from
589
- `assignment['signing_urls']`: they accept the terms, confirm their data, and sign with their A1 or A3 certificate
590
- through the Web PKI browser extension. The ordinary signing endpoint rejects certificate signers, and the SDK does
591
- not wrap the Web PKI handshake (`/signers/certificate/start`, `/signers/certificate/complete`), whose schemas are
592
- not part of the OpenAPI contract. Once it completes, the `pades` artifact returns the qualified signature.
593
-
594
- ### 7. Receive webhooks
595
-
596
- An account can have 1 webhook endpoint, or up to 3 on paid plans. Each has its own distinct URL, event list, and
597
- signing setting, and every active endpoint subscribed to an event receives it.
598
-
599
- ```ruby
600
- client.webhooks.list_event_types # => [{ 'id' => 'document_ready', 'description' => '...' }, ...]
601
-
602
- endpoint = client.webhooks.create_endpoint(
603
- url: 'https://app.example.com/webhooks/assinafy',
604
- email: 'ops@example.com', # delivery-failure notices
605
- events: %w[document_ready signer_signed_document signer_rejected_document],
606
- name: 'ERP',
607
- signing_enabled: true
608
- )
609
- secret = endpoint.fetch('secret') # returned once on creation; store it immediately, including for OAuth apps
610
- ```
611
-
612
- - `create_endpoint` requires `url`, `email`, and `events`; `name`, `is_active` (default `true`), and
613
- `signing_enabled` (default `false`) are optional. Unknown keys raise `ValidationError` locally.
614
- - Creating one past the plan limit answers `403`; a URL another endpoint already uses answers `400`.
615
- - `update_endpoint(id, payload)` changes only the fields sent. `signing_enabled: true` creates a secret when the
616
- endpoint has none and keeps the current one otherwise; `false` discards it.
617
- - `rotate_endpoint_secret(id)` returns a new secret; the old one stops working immediately. Pass
618
- `keep_previous: true` for 24 hours of signatures from both secrets while receivers switch.
619
- - Reading a secret requires an API key or user session. Rotation is available to OAuth apps with
620
- `webhooks:write`, including recovery of a lost secret. Both methods answer `400` when signing is disabled.
621
- - Enabling signing with `update_endpoint` returns the new secret once. Store it before using the endpoint.
622
- - `list_endpoints(url: registered_url)` filters by exact URL; `delete_endpoint_by_url(registered_url)` removes
623
- that endpoint and returns `nil` (`404` when no endpoint matches).
624
-
625
- **Delivery contract.** Each delivery is a `POST` with an `application/json` body and the headers `webhook-id`
626
- (identical on every attempt of the same event to the same endpoint — deduplicate on it), `webhook-timestamp`
627
- (Unix seconds), and, when signing is enabled, `webhook-signature`. Any `2xx` is success. Network failures,
628
- timeouts, `408`, `429` and `5xx` get up to six attempts about ten minutes apart; other statuses are final.
629
- After ten failed deliveries in a row the endpoint pauses. Probes follow after 3, 15 and 60 minutes, then every
630
- six hours; success releases queued events oldest first. Updating its URL or setting `is_active: true` also lifts
631
- the pause. `retry_dispatch` sends now; `test_endpoint` sends a separate `webhook_test` without changing the pause.
632
- Delivery history is retained for seven days and captures the first 2000 response-body characters.
633
-
634
- **Verifying signatures.** Signatures follow [Standard Webhooks](https://www.standardwebhooks.com): space-separated
635
- `v1,<base64 HMAC-SHA256>` entries over `"{webhook-id}.{webhook-timestamp}.{raw body}"`, keyed with the
636
- base64-decoded part of the secret after `whsec_`. `verify_delivery` checks them in constant time and rejects
637
- timestamps more than 5 minutes from the local clock (`tolerance:` changes the window):
638
-
639
- ```ruby
640
- class AssinafyWebhooksController < ActionController::API
641
- VERIFIER = Assinafy::Support::WebhookVerifier.new(ENV.fetch('ASSINAFY_WEBHOOK_SECRET'))
642
-
643
- def create
644
- raw_body = request.raw_post
645
- return head(:unauthorized) unless VERIFIER.verify_delivery(raw_body, request.headers)
646
-
647
- webhook_id = request.headers['webhook-id']
648
- return head(:ok) if AssinafyEvent.exists?(webhook_id: webhook_id) # already processed
649
-
650
- event = VERIFIER.extract_event(raw_body)
651
- AssinafyEvent.create!(webhook_id: webhook_id, kind: VERIFIER.event_type(event), body: raw_body)
652
- ProcessAssinafyEventJob.perform_later(webhook_id)
653
- head :ok
654
- end
655
- end
656
- ```
657
-
658
- In plain Rack (Sinatra, Roda), pass the env: `VERIFIER.verify_delivery(request.body.read, request.env)` — the
659
- `HTTP_WEBHOOK_ID` form is accepted, as is a plain Hash. `verify_delivery` returns `false` — never raises — for a
660
- missing or malformed secret, a missing header, a wrong signature, or a stale timestamp. Always pass the **raw**
661
- body exactly as received. `client.webhook_verifier` is a verifier built from the client's `webhook_secret`.
662
-
663
- `extract_event` parses the body (or returns `nil`); `event_type`, `event_payload`, `event_object` (the entity acted
664
- on), and `event_subject` (the actor) read the envelope `{ id, event, message, payload, origin, created_at,
665
- subject, object, account_id }`. `subject` and `object` carry a `type` (`User`, `Signer`, `Account`, `Document`, or
666
- `Template`); body timestamps are Unix seconds.
667
-
668
- `verify(raw_body, hex_signature)` remains only for receivers whose own gateway signs bodies with a hex
669
- HMAC-SHA256 shared secret.
670
-
671
- Give the webhook event table a unique index on `webhook_id`, process events idempotently, and arrange durable
672
- job delivery before acknowledging the request so concurrent retries or a failed enqueue cannot lose an event.
673
-
674
- ### 8. Track progress, download, and verify
675
-
676
- ```ruby
677
- document_id = document.fetch('id')
678
-
679
- client.documents.signing_progress(document_id) # => { signed: 1, total: 2, pending: 1, percentage: 50.0 }
680
- client.documents.fully_signed?(document_id)
681
- client.documents.activities(document_id) # => one page of Array<DocumentActivity>
682
- client.documents.activities_page(document_id, page: 1, per_page: 20) # => { data:, meta: }
683
-
684
- signed_pdf = client.documents.download(document_id, 'certificated')
685
- # also 'original', 'certificate-page', 'bundle' (zip), and 'pades' for certificate-signed documents
686
-
687
- verification = client.documents.verify('signature-hash-from-assinafy')
688
- verification['is_valid'] # => true
689
- verification['agreement_code'] # printed on the document certificate
690
- ```
691
-
692
- `verify` returns Assinafy's verification result. It does not independently validate the PDF signature or its
693
- certificate chain; see [Authentication and safety](docs/API_REFERENCE.md#authentication-and-safety).
694
-
695
- ### 9. Clean up
696
-
697
- ```ruby
698
- client.documents.delete(document_id)
699
- client.signers.delete(signer.fetch('id'))
700
- client.webhooks.delete_endpoint(endpoint.fetch('id'))
701
- ```
702
-
703
- Delete only resources your application owns, after downstream work is complete; keep shared signer and template
704
- data. Some resources return `409` while processing or while still referenced.
705
-
706
- ### 10. Handle errors
707
-
708
- ```ruby
709
- begin
710
- client.documents.details(document_id)
711
- rescue Assinafy::ValidationError => e
712
- warn e.errors.inspect
713
- rescue Assinafy::ApiError => e
714
- warn "Assinafy returned #{e.status_code}: #{e.message}"
715
- sleep(e.retry_after) if e.status_code == 429 && e.retry_after # also e.rate_limit => { limit:, remaining:, reset: }
716
- rescue Assinafy::NetworkError => e
717
- warn "Network failure: #{e.message}"
718
- end
719
- ```
720
-
721
- See [Errors](#errors) for the full hierarchy.
722
-
723
- ## Resource reference
724
-
725
- `Assinafy::Client` exposes the API resources below plus the local `webhook_verifier` helper:
726
-
727
- | Accessor | What it covers |
728
- | --------------------------- | ------------------------------------------------------------------ |
729
- | `client.auth` | Login, two-factor authentication, social login, passwords, API keys |
730
- | `client.oauth` | OAuth 2.1 token exchange, refresh, revocation, userinfo, discovery |
731
- | `client.accounts` | Account CRUD, theme, KPI stats, brand logo |
732
- | `client.users` | User profile, notification preferences, cross-account KPIs |
733
- | `client.documents` | Upload, list, search, rename, download, delete, verify, tags |
734
- | `client.envelopes` | Send several documents together, estimate, reorder, cancel and download |
735
- | `client.contracts` | Contract terms, amendments, renewals, terminations |
736
- | `client.signers` | Workspace signer CRUD + signer self-service endpoints |
737
- | `client.signer_documents` | Signer-authenticated multi-document operations + search |
738
- | `client.assignments` | List/create/sign/decline/resend/estimate assignments |
739
- | `client.templates` | Template creation (file upload), get, list, update, delete |
740
- | `client.tags` | Workspace tags |
741
- | `client.fields` | Field definitions + validation + type catalog |
742
- | `client.webhooks` | Webhook endpoints, signing secrets, event catalog, deliveries, retries |
743
- | `client.webhook_verifier` | Standard Webhooks signature verification for received deliveries |
744
-
745
- ### Accounts
746
-
747
- ```ruby
748
- client.accounts.list # { data: [...] } — no pagination meta
749
- client.accounts.get # the current account (or pass an id)
750
- client.accounts.get(expand: 'signing_features') # includes available signing features
751
- client.accounts.create(name: 'Acme Inc.')
752
- client.accounts.update({ name: 'Acme Renamed' })
753
- client.accounts.delete(force: true, account_id_override: 'account-id')
754
- client.accounts.theme # { account_name, primary_color, secondary_color, logo }
755
- client.accounts.stats(granularity: 'monthly', month: '2026-06') # account KPI rows
756
- client.accounts.upload_logo({ file_path: './logo.png' })
757
- client.accounts.download_logo # raw bytes; raises ApiError on HTTP 404 when unset
758
- client.accounts.delete_logo
759
- client.accounts.usage # { 'plan' => ..., 'documents_renewal_date' => ..., 'balances' => { ... } }
760
- client.accounts.notification_policy # { 'editable' => true, 'owners_receive_all' => false, 'events' => { ... } }
761
- client.accounts.update_notification_policy(events: { SignerViewed: false }, owners_receive_all: true)
762
- ```
763
-
764
- Usage and notification policy are unavailable to third-party OAuth applications. Policy writes require an owner;
765
- they merge only supplied event flags. A disabled workspace event suppresses it across channels even when a
766
- member enables it. `SignerIdentityReviewRequired: false` disables only push; its email is always sent.
767
-
768
- ### Users
769
-
770
- ```ruby
771
- client.users.me
772
- client.users.stats(granularity: 'daily', month: '2026-06') # cross-account KPI rows
773
- client.users.notification_preferences # returns all thirteen owner-email preferences
774
- client.users.update_notification_preferences(SignerDeclined: false) # partial request; returns all thirteen
775
- client.users.push_preferences # eight phone-push preferences; separate from email
776
- client.users.update_push_preferences(SignerViewed: false) # partial request; returns the full push map
777
- ```
154
+ | `verification_method` | Notification | Requirements | Cost per signer |
155
+ | --- | --- | --- | --- |
156
+ | `Email` (default) | `Email` | email | 0 |
157
+ | `Whatsapp` | `Whatsapp` | `whatsapp_phone_number`, paid plan | WhatsApp notification (0.4 on Pro, 0.45 otherwise) |
158
+ | `DigitalCertificate` | `Email` or `Whatsapp` | CPF/CNPJ in `government_id`, `virtual` only, alone in its step | plan price + notification |
159
+ | `IdDocumentFaceMatchBasic` | `Email` or `Whatsapp` | valid CPF, account feature | 0.25 to 1.5 by plan + notification |
778
160
 
779
- Email and push preferences apply to the user across workspaces. They accept boolean values and reject unknown
780
- keys or an empty update. These personal settings are unavailable to third-party OAuth applications.
161
+ Prices depend on the plan; `estimate_cost` returns the exact charge with its breakdown. Send exactly one
162
+ notification method per signer. Steps are all-or-none, positive and contiguous from 1; equal
163
+ steps sign in parallel. Deadlines are zoned ISO 8601 and at least an hour ahead. `sign_as` records a signing
164
+ capacity (`AssignmentResource::SIGNER_CAPACITIES`). The SDK checks all of this locally before any request.
781
165
 
782
- Both stats methods validate `granularity` (`monthly` or `daily`) and `month` (`YYYY-MM`) locally; daily statistics
783
- require `month`. They return rows
784
- with `period`, `documents_uploaded`, `documents_sent`, `signature_requests`,
785
- `signature_requests_notification_email`, `signature_requests_notification_whatsapp`,
786
- `signature_requests_notification_bypass`, `signature_requests_verification_email`,
787
- `signature_requests_verification_whatsapp`, `signature_requests_verification_bypass`,
788
- `signature_requests_verification_digital_certificate`, `signature_requests_viewed`,
789
- `signature_requests_completed`, and `documents_certified`.
166
+ - **Biometric:** the signer consents with `signers.start_identity_verification(consent: true,
167
+ signer_access_code:)` and opens the returned capture URL unchanged (it is a bearer link). An account reviewer
168
+ uses `assignments.identity_review`, `identity_review_image` and `decide_identity_review`; a rejection cancels
169
+ the document.
170
+ - **A1/A3 certificate:** the signer completes the hosted Web PKI flow from `signing_urls`; the `pades` artifact
171
+ carries the qualified signature.
172
+ - **Signer side:** calls take `signer_access_code:` and never send workspace credentials. Virtual assignments
173
+ sign with `assignments.sign(document_id, assignment_id, [], signer_access_code:)`; collect assignments first
174
+ store signature and initial images (PNG or JPEG) and send the field values.
790
175
 
791
- ### Documents
176
+ ### Templates, envelopes and scheduled sends
792
177
 
793
178
  ```ruby
794
- client.documents.statuses # GET /documents/statuses
795
- client.documents.list(page: 1, per_page: 20, status: 'pending_signature')
796
- client.documents.list(tags: ['tag-id-1', 'tag-id-2']) # documents carrying every listed tag
797
- client.documents.list(envelope_id: 'envelope-id') # documents in an envelope
798
- client.documents.search('contract') # lightweight GET .../documents/search
799
- client.documents.upload({ file_path: './contract.pdf' }) # named after the file
800
- client.documents.upload({ buffer: pdf_bytes, file_name: 'contract.pdf' })
801
- client.documents.rename('document-id', 'renamed.pdf') # PATCH /documents/{id}
802
- client.documents.get('document-id') # alias of .details
803
- client.documents.details('document-id', expand: ['envelope_id', 'envelope'])
804
- client.documents.wait_until_ready('document-id', max_wait_seconds: 60)
805
- client.documents.activities('document-id')
806
- client.documents.activities_page('document-id', sort: '-id', page: 1, per_page: 20)
807
- client.documents.thumbnail('document-id') # binary PNG/JPEG
808
- client.documents.thumbnail('document-id', artifact: 'certificated') # rendered signed content
809
- client.documents.download('document-id', 'certificated') # binary PDF
810
- client.documents.download('document-id', 'pades') # signed PAdES artifact
811
- client.documents.download_page('document-id', 'page-id')
812
- client.documents.download_page('document-id', 'page-id', artifact: 'certificated')
813
- client.documents.delete('document-id')
814
- client.documents.verify('signature-hash')
815
- client.documents.public_info('document-id')
816
- client.documents.send_token('document-id', recipient: 'signer@example.com')
817
- client.documents.list_tags('document-id')
818
- client.documents.replace_tags('document-id', ['tag-id-1', 'tag-id-2'])
819
- client.documents.append_tags('document-id', ['tag-id-3'])
820
- client.documents.detach_tag('document-id', 'tag-id')
821
-
822
- client.documents.create_from_template(
823
- 'template-id',
824
- [{ role_id: 'role-id', id: 'signer-id', verification_method: 'Email', notification_methods: ['Email'] }],
825
- { name: 'Contract', message: 'Please sign', expires_at: '2099-12-31T23:59:00Z' }
826
- )
827
- client.documents.estimate_cost_from_template('template-id', [{ role_id: 'role-id', verification_method: 'Whatsapp' }])
828
-
829
- client.documents.fully_signed?('document-id')
830
- client.documents.signing_progress('document-id') # => { signed: 1, total: 2, pending: 1, percentage: 50.0 }
831
- ```
832
-
833
- An Array `tags` filter is sent as comma-separated tag IDs. The tag arrays of `replace_tags`/`append_tags` take tag
834
- IDs.
835
-
836
- Activities default to twenty per page. `activities` preserves the Array return; `activities_page` exposes the
837
- pagination headers so callers can traverse every event. Signed thumbnails/pages use `artifact: 'certificated'`
838
- with workspace credentials. The first render can wait up to thirty seconds, then return `503` with `Retry-After`;
839
- the SDK does not retry. These renders carry `Cache-Control: no-store`. Certificate pages have no document page
840
- IDs, and the qualified certificate seal is available in the `pades` artifact.
179
+ client.documents.create_from_template('template-id', [{ role_id: 'role-id', id: signer.fetch('id') }],
180
+ { name: 'Contract', idempotency_key: 'request-id' })
841
181
 
842
- ### Envelopes
843
-
844
- Send up to 20 prepared documents to up to 20 existing signers in one invitation. Each document retains its own
845
- assignment, status and artifacts. All envelope signers sign in parallel; no `step` is accepted.
846
-
847
- ```ruby
848
- request = {
849
- name: 'Agreement and annex',
850
- signers: [{ id: 'signer-id', verification_method: 'Email', notification_methods: ['Email'] }],
851
- documents: [
852
- { id: 'agreement-id', signer_ids: ['signer-id'] },
853
- { id: 'annex-id', signer_ids: ['signer-id'] }
854
- ]
855
- }
856
- estimate = client.envelopes.estimate_cost(request)
857
182
  envelope = client.envelopes.create(
858
- request.merge(max_total_credits: estimate.fetch('total_credits')), idempotency_key: 'envelope-request-id'
859
- )
860
- # => { 'id' => 'envelope-id', 'name' => 'Agreement and annex', 'message' => nil,
861
- # 'documents' => [...], 'counts' => { 'pending_signature' => 2 },
862
- # 'signing_urls' => [...], 'created_at' => '2026-11-11T12:00:00Z' }
863
-
864
- client.envelopes.list(status: 'open') # { data: [...], meta: { ... } }
865
- client.envelopes.get(envelope.fetch('id'))
866
- client.envelopes.update(envelope.fetch('id'), document_ids: %w[annex-id agreement-id], message: nil)
867
- client.envelopes.activities(envelope.fetch('id')) # paginated events with document_id/document_name
868
- client.envelopes.resend_notification(envelope.fetch('id'), 'signer-id') # { 'is_sent' => true, ... }
869
- client.envelopes.add_document(envelope.fetch('id'), id: 'extra-document-id', signer_ids: ['signer-id'])
870
- client.envelopes.remove_document(envelope.fetch('id'), 'extra-document-id') # cancels and removes that open document
871
- archive = client.envelopes.download(envelope.fetch('id'), 'original') # ZIP bytes in envelope order
872
- client.envelopes.cancel(envelope.fetch('id')) # [{ 'id' => ..., 'status' => ..., 'cancelled' => true }]
873
- client.envelopes.delete(envelope.fetch('id')) # nil; closed envelopes only, documents remain
874
- ```
875
-
876
- `collect` documents add positioned `entries` whose field signers exactly match `signer_ids`. Every envelope
877
- signer must appear on a document. A certificate signer signs alone on each virtual document and is charged per
878
- document; a biometric signer verifies once for the envelope. Preserve the creation idempotency key after an
879
- ambiguous response. `max_total_credits` prevents creating or charging an envelope above the approved cost.
880
-
881
- ### Embedded signing
882
-
883
- Requires the account's Embed feature and an API key or user session; third-party OAuth cannot create sessions.
884
- Register exact allowed origins, then mark the signer `embedded: true` with Email or Whatsapp verification:
885
-
886
- ```ruby
887
- origin = client.accounts.create_embed_origin('https://app.example.com')
888
- # => { 'id' => 'origin-id', 'origin' => 'https://app.example.com', 'created_at' => '2026-11-11T12:00:00Z' }
889
- client.accounts.list_embed_origins
890
- client.accounts.update_embed_origin(origin.fetch('id'), 'https://sign.example.com')
891
-
892
- assignment = client.assignments.create(
893
- 'document-id', method: 'virtual',
894
- signers: [{ id: 'signer-id', verification_method: 'Email', notification_methods: ['Email'], embedded: true }]
895
- )
896
- session = client.assignments.create_embed_session('document-id', assignment.fetch('id'), 'signer-id')
897
- # => { 'url' => 'https://app.assinafy.com.br/embed/session-token', 'expires_at' => '2026-11-11T12:05:00Z' }
898
- # Pass session['url'] only to the intended signer's page and load it in an iframe.
899
- client.accounts.delete_embed_origin(origin.fetch('id')) # nil; removes that embedding permission
900
- ```
901
-
902
- Origins have no path, query, fragment or wildcard; HTTPS is required except HTTP localhost/127.0.0.1.
903
- At most ten origins are allowed. Mint a fresh single-use URL for each frame display; it expires after five
904
- minutes. `signing_urls` contains `url: nil, embedded: true` for embedded signers; invitations still deliver their
905
- code. Follow the live [Embedded Signing Guide](https://api.assinafy.com.br/v1/docs) for the `assinafy:hello`
906
- handshake and validate both `postMessage` origin and iframe window. Confirm completion through a webhook or
907
- document read; frame events alone do not authorize application actions.
908
-
909
- `assignments.exchange_embed_session(token, parent_origin:)` is the token-only operation used by the Assinafy
910
- embed page. An ordinary integration loads the session URL; it does not exchange the token itself or expose the
911
- returned signer access code. Resend the code through `assignments.resend_notification` from your backend.
912
-
913
- ### Contracts
914
-
915
- ```ruby
916
- contract = client.contracts.update(
917
- 'document-id',
918
- status: 'active', counterparty_name: 'Example Ltda', value: 120_000, currency: 'BRL',
919
- start_date: '2026-11-01', end_date: '2027-10-31', auto_renew: true,
920
- renewal_term_months: 12, notice_period_days: 30
183
+ { name: 'Agreement and annex', signers: [{ id: signer.fetch('id') }],
184
+ documents: [{ id: 'document-1', signer_ids: [signer.fetch('id')] },
185
+ { id: 'document-2', signer_ids: [signer.fetch('id')] }] },
186
+ idempotency_key: 'request-id'
921
187
  )
922
188
 
923
- client.contracts.get('document-id')
924
- client.contracts.list(status: ['active'], ending_within_days: 30)
925
- client.contracts.related('document-id')
926
- client.contracts.related('document-id', expand: 'document') # also includes the parent document
927
- client.contracts.renew('document-id', term: contract['term'], updated_at: contract['updated_at'])
928
- client.contracts.terminate('document-id', reason: 'Ended by the parties')
189
+ scheduled = client.assignments.schedule(document.fetch('id'), request, send_at: (Time.now + 7200).utc.iso8601)
190
+ client.scheduled_sends.list # also cancel(id) and send_now(id)
929
191
  ```
930
192
 
931
- `update` is partial and preserves explicit `nil` values as JSON `null`. Link an amendment document with
932
- `parent_document_id` and `relation_type`. Reads require OAuth scope `documents:read`; writes require
933
- `documents:write` and a plan with contract tracking. `get` and `related` return `nil` when no tracked terms exist.
193
+ A template document starts `uploaded` with `assignment: nil`; follow it until `pending_signature`. Envelopes group
194
+ up to 20 documents and 20 signers, and `envelopes.schedule` schedules one. A scheduled send creates and charges
195
+ nothing until delivery, one hour to 90 days ahead. Keep the same idempotency key after a lost response;
196
+ `max_total_credits` refuses a creation above the approved cost with `409 CreditCeilingExceeded`.
934
197
 
935
- ### Signers (workspace CRUD)
198
+ `documents.set_watchers` adds up to ten contacts who receive the final status, `documents.signer_capacities` reads
199
+ `sign_as`, and `documents.notification_history` reports delivery and opens.
936
200
 
937
- ```ruby
938
- client.signers.create(full_name: 'Alice Silva', email: 'alice@example.com')
939
- client.signers.create(full_name: 'Bob Costa', phone: '+5500000000000') # phone -> whatsapp_phone_number
940
- client.signers.create(full_name: 'Carla Lima', email: 'carla@example.com', government_id: '00000000000')
941
- client.signers.validate_create!(full_name: 'Alice Silva', email: 'alice@example.com') # no request
942
- client.signers.get('signer-id')
943
- client.signers.list(search: 'alice', per_page: 50) # returns { data:, meta: }
944
- client.signers.update('signer-id', full_name: 'Alice S.', government_id: '00000000000')
945
- client.signers.delete('signer-id')
946
- client.signers.find_by_email('alice@example.com') # case-insensitive; nil when no match
947
- ```
201
+ ### Embedded signing
948
202
 
949
- ### Signers (self-service, signer-access-code)
203
+ With the Embed feature and an API key, register exact origins with
204
+ `accounts.create_embed_origin('https://app.example.com')`, create Email/Whatsapp signers with `embedded: true`,
205
+ then mint a five-minute, single-use URL from your backend each time the frame is shown:
950
206
 
951
207
  ```ruby
952
- client.signers.self_data(signer_access_code: 'code') # includes has_signature, has_initial, is_signature_reusable
953
- client.signers.accept_terms(signer_access_code: 'code')
954
- client.signers.verify_email(verification_code: '123456', signer_access_code: 'code')
955
- client.signers.confirm_data('document-id', { email: 'alice@example.com', has_accepted_terms: true }, signer_access_code: 'code')
956
- client.signers.upload_signature(png_bytes, signer_access_code: 'code', type: 'signature', content_type: 'image/png')
957
- client.signers.download_signature(signer_access_code: 'code', type: 'signature')
958
- client.signers.theme(signer_access_code: 'code') # account_name, primary_color, secondary_color, logo
959
- client.signers.download_logo(signer_access_code: 'code') # binary image; 404 when unset
208
+ session = client.assignments.create_embed_session(document_id, assignment_id, signer_id)
209
+ session['url'] # load in an iframe; confirm the outcome through webhooks or a document read
960
210
  ```
961
211
 
962
- ### Assignments
212
+ ### Webhooks
963
213
 
964
214
  ```ruby
965
- # Virtual (no positioned fields)
966
- client.assignments.create(
967
- 'document-id',
968
- method: 'virtual',
969
- signers: [{ id: 'signer-1', verification_method: 'Email', notification_methods: ['Email'], step: 1 }],
970
- message: 'Please sign',
971
- expires_at: '2099-12-31T23:59:00Z',
972
- copy_receivers: ['cc-signer-id']
215
+ endpoint = client.webhooks.create_endpoint(
216
+ url: 'https://app.example.com/webhooks/assinafy', email: 'ops@example.com',
217
+ events: %w[document_ready signer_signed_document signer_rejected_document], signing_enabled: true
973
218
  )
219
+ secret = endpoint.fetch('secret') # returned once; store it
974
220
 
975
- # Collect (positioned fields)
976
- client.assignments.create(
977
- 'document-id',
978
- method: 'collect',
979
- signers: [{ id: 'signer-1' }],
980
- entries: [{ page_id: 'page-id', fields: [{ signer_id: 'signer-1', field_id: 'field-id',
981
- display_settings: { left: 100, top: 100, width: 240,
982
- height: 48, fontSize: 16 } }] }]
983
- )
221
+ verifier = Assinafy::Support::WebhookVerifier.new(secret)
222
+ return head(:unauthorized) unless verifier.verify_delivery(request.raw_post, request.headers)
984
223
 
985
- client.assignments.list # GET /assignments (scoped to the account)
986
- client.assignments.estimate_cost('document-id', signers: [{ verification_method: 'Whatsapp' }])
987
- client.assignments.reset_expiration('document-id', 'assignment-id', '2099-12-31T23:59:00Z')
988
- client.assignments.reset_expiration('document-id', 'assignment-id', nil) # clears the expiry
989
- client.assignments.resend_notification('document-id', 'assignment-id', 'signer-id')
990
- client.assignments.estimate_resend_cost('document-id', 'assignment-id', 'signer-id')
991
- client.assignments.whatsapp_notifications('document-id', 'assignment-id')
992
-
993
- # Signer perspective (signer-access-code authentication)
994
- client.assignments.signer_document(signer_access_code: 'code', has_accepted_terms: true)
995
- client.assignments.sign('document-id', 'assignment-id',
996
- [{ item_id: 'i1', field_id: 'f1', page_id: 'p1', value: 'Alice' }],
997
- signer_access_code: 'code')
998
- client.assignments.decline('document-id', 'assignment-id', decline_reason: 'Clause 2', signer_access_code: 'code')
224
+ event = verifier.extract_event(request.raw_post) # dedupe on the webhook-id header
999
225
  ```
1000
226
 
1001
- The `sign` body is the API's camelCase exception: the SDK maps `item_id`/`field_id`/`page_id` to
1002
- `itemId`/`fieldId`/`pageId` (camelCase input passes through). Assignment listing sends the camelCase `accountId`
1003
- query parameter.
227
+ Verification follows Standard Webhooks with a 300-second tolerance. `rotate_endpoint_secret(id, keep_previous:
228
+ true)` keeps both secrets signing for 24 hours. OAuth apps cannot read a secret but can rotate it with
229
+ `webhooks:write`.
1004
230
 
1005
- ### Signer documents (multi-document workflows)
231
+ ### Progress, artifacts, contracts and cleanup
1006
232
 
1007
233
  ```ruby
1008
- client.signer_documents.current('signer-id', signer_access_code: 'code')
1009
- client.signer_documents.list('signer-id', { status: 'pending_signature' }, signer_access_code: 'code')
1010
- client.signer_documents.search('signer-id', 'contract', signer_access_code: 'code')
1011
- client.signer_documents.list_as_workspace('signer-id') # same route with your API key
1012
- client.signer_documents.search_as_workspace('signer-id', 'contract')
1013
- client.signer_documents.sign_multiple(%w[document-id-1 document-id-2], signer_access_code: 'code')
1014
- client.signer_documents.decline_multiple(%w[document-id-1 document-id-2], decline_reason: 'No', signer_access_code: 'code')
1015
- client.signer_documents.download('signer-id', 'document-id', signer_access_code: 'code') # original PDF only
1016
- client.signer_documents.send_certified_copy(signer_access_code: 'code', document_id: 'document-id')
1017
- # => { 'available' => true, 'notification_method' => 'Email', 'resends_left' => 2, 'sent_to' => 'a***@example.com' }
1018
- client.signer_documents.download_certified_copy('download-token', pades: false) # binary PDF, token only
1019
- client.signer_documents.resend_certified_copy('download-token') # delivery metadata as above
1020
- ```
1021
-
1022
- Signer downloads require the access code and serve only `original`; use the workspace download API for other
1023
- artifacts. Certified copies are delivered by email or WhatsApp with their own download token. An expired token's
1024
- `302` is exposed as `ApiError`; the SDK does not follow it. For an envelope, pass `document_id` when selecting a
1025
- document or requesting its copy; `assignments.signer_document(expand: 'envelope', signer_access_code: 'code')`
1026
- includes the envelope's remaining documents.
234
+ client.documents.signing_progress(document.fetch('id')) # => { signed: 1, total: 2, pending: 1, percentage: 50.0 }
235
+ pdf = client.documents.download(document.fetch('id'), 'certificated')
236
+ client.documents.verify('signature-hash')['is_valid']
1027
237
 
1028
- ### Templates
238
+ terms = client.contracts.get(document.fetch('id')) # nil when the document has no contract terms
239
+ client.contracts.update(document.fetch('id'), { end_date: '2027-12-31', updated_at: terms&.fetch('updated_at') })
1029
240
 
1030
- ```ruby
1031
- client.templates.list(search: 'contract', per_page: 25)
1032
- client.templates.get('template-id')
1033
- client.templates.create({ file_path: './contract.pdf' }) # multipart upload, up to 25 MB
1034
- client.templates.create({ buffer: pdf_bytes, file_name: 'contract.pdf' })
1035
- client.templates.update('template-id', name: 'Renamed template')
1036
- client.templates.delete('template-id')
1037
- client.templates.download_page('template-id', 'page-id') # binary image bytes
241
+ client.documents.cancel(document.fetch('id')) # stop signing, keep the document
242
+ client.documents.delete(document.fetch('id'))
1038
243
  ```
1039
244
 
1040
- `get`, `create`, `update`, `delete`, and `download_page` are supported by the deployed API beyond the OpenAPI
1041
- document. `create` requires a source file; the template name defaults to the file's name. Template generation
1042
- needs one entry per role, using a distinct existing signer ID or an `email`/`name` pair;
1043
- `role_id` comes from the template's `roles`. Cost estimation requires `role_id` but can omit the signer ID.
1044
-
1045
- ### Tags
245
+ Contract writes need a plan with contract tracking; pass the `updated_at` you read so a concurrent change answers
246
+ `409` instead of being overwritten. `cancel` moves a pending document to `rejected_by_user` and notifies its
247
+ signers; documents of an open envelope are cancelled through the envelope.
1046
248
 
1047
- ```ruby
1048
- client.tags.list(search: 'contract')
1049
- client.tags.create(name: 'Contracts', color: 'ff8800')
1050
- client.tags.update('tag-id', name: 'Sales Contracts', color: nil) # nil clears the color
1051
- client.tags.delete('tag-id') # fails with 409 if the tag is in use
1052
- client.tags.delete('tag-id', force: true) # detaches from documents/templates first
1053
- ```
249
+ ## Responses and errors
1054
250
 
1055
- ### Fields
251
+ Methods return the unwrapped `data` of the `{ status, message, data }` envelope. Paginated lists return
252
+ `{ data:, meta: }` (`per_page:` becomes `per-page`), simple lists return an `Array`, downloads return a binary
253
+ `String`, and empty successes return `nil`. OAuth endpoints return their RFC objects unchanged.
1056
254
 
1057
- ```ruby
1058
- client.fields.types # GET /field-types
1059
- client.fields.list(include_inactive: true, include_standard: false)
1060
- client.fields.create(type: 'text', name: 'Internal code', regex: '/[A-Z]{3}-[0-9]{4}/')
1061
- client.fields.get('field-id')
1062
- client.fields.update('field-id', name: 'Renamed')
1063
- client.fields.delete('field-id')
1064
-
1065
- client.fields.validate('field-id', 'ABC-1234') # workspace user
1066
- client.fields.validate('field-id', 'ABC-1234', signer_access_code: 'code') # signer
1067
- client.fields.validate_multiple(
1068
- [{ field_id: 'field-id-1', value: '1' }, { field_id: 'field-id-2', value: 'value@example.com' }],
1069
- signer_access_code: 'code'
1070
- )
1071
- ```
1072
-
1073
- ### Webhooks
1074
-
1075
- ```ruby
1076
- client.webhooks.list_event_types # GET /webhooks/event-types
1077
- client.webhooks.list_endpoints # oldest first
1078
- client.webhooks.create_endpoint(url: 'https://example.com/webhooks/assinafy', email: 'ops@example.com',
1079
- events: %w[document_ready], signing_enabled: true)
1080
- client.webhooks.get_endpoint('webhook-endpoint-id')
1081
- client.webhooks.update_endpoint('webhook-endpoint-id', is_active: false)
1082
- client.webhooks.delete_endpoint('webhook-endpoint-id') # => nil
1083
- client.webhooks.endpoint_secret('webhook-endpoint-id') # => { 'secret' => 'whsec_...' }
1084
- client.webhooks.rotate_endpoint_secret('webhook-endpoint-id')
1085
- client.webhooks.rotate_endpoint_secret('webhook-endpoint-id', keep_previous: true) # 24-hour overlap
1086
- client.webhooks.test_endpoint('webhook-endpoint-id') # one manual delivery; returns its dispatch entry
1087
-
1088
- client.webhooks.list_dispatches(endpoint_id: 'webhook-endpoint-id', delivered: false, per_page: 50)
1089
- client.webhooks.retry_dispatch('dispatch-id')
1090
-
1091
- # Subscription operations act on the account's oldest endpoint:
1092
- client.webhooks.get # nil on 404
1093
- client.webhooks.register(url: 'https://example.com/webhooks/assinafy', email: 'ops@example.com',
1094
- events: %w[document_ready signer_signed_document])
1095
- client.webhooks.inactivate # stop deliveries, keep the event set
1096
- ```
1097
-
1098
- `register` accepts only `url`, `email`, `events`, and `is_active`; other keys raise `ValidationError`. Use the
1099
- endpoint operations for names, signing, and several endpoints.
1100
-
1101
- ## Responses
1102
-
1103
- Most JSON successes use a `{ "status": ..., "message": ..., "data": ... }` envelope. The SDK
1104
- returns the `data` payload (a Hash for single resources, an Array for collection bodies). For
1105
- documented no-data envelopes containing only `status`/`message`, it returns `nil`; deployed API
1106
- versions that add `data` are passed through. Binary endpoints (`download`, `thumbnail`,
1107
- `download_page`, `download_signature`) return raw bytes as an ASCII-8BIT `String`, and
1108
- delete-style endpoints return `nil`.
1109
-
1110
- OAuth endpoints are the exception: `/oauth/token`, `/oauth/revoke`, `/oauth/userinfo`, and the `.well-known`
1111
- metadata documents answer with flat RFC 6749 / OIDC / RFC 8615 objects rather than the envelope, and the SDK
1112
- returns those bodies unchanged.
1113
-
1114
- The [SDK API reference](docs/API_REFERENCE.md) maps every API operation to its Ruby method and documents exact
1115
- authentication, parameters, request bodies, success responses, and every published schema property.
1116
-
1117
- ## Pagination
1118
-
1119
- Most `*.list*` methods return `{ data: [...], meta: { ... } }` when the API includes pagination
1120
- headers. Ruby-style `per_page:` is transparently converted to the documented `per-page` query
1121
- parameter (values above the API's maximum are clamped server-side). Endpoints that send no pagination headers
1122
- (e.g. `accounts.list`) return `{ data: [...] }` without `meta`.
1123
-
1124
- ```ruby
1125
- result = client.documents.list(page: 2, per_page: 25)
1126
- result[:data] # => Array<Hash>
1127
- result[:meta] # => { current_page: 2, per_page: 25, total: 138, last_page: 6 }
1128
- ```
1129
-
1130
- ## Errors
1131
-
1132
- The SDK raises one of:
1133
-
1134
- - `Assinafy::ValidationError` — caller-side input invalid (missing IDs, bad email, etc.), raised before any request.
1135
- - `Assinafy::ApiError` — the API returned a non-2xx status. Includes `status_code`, `message`, `error_name`,
1136
- `error_code`, and `response_data`; on a `403`, `context[:www_authenticate]` names the scope an OAuth token is
1137
- missing.
1138
- - `Assinafy::OAuthError` — an OAuth endpoint failed. Subclasses `ApiError`, and adds `error` and
1139
- `error_description` from the flat RFC 6749 body.
1140
- - `Assinafy::NetworkError` — Faraday connection error, timeout, or TLS failure.
1141
- - `Assinafy::Error` — base class; other unexpected errors get wrapped here with the operation label.
1142
-
1143
- All inherit a `#context` Hash with debugging metadata.
1144
-
1145
- Use `ApiError#error_code` for actionable refusals such as `PlanRestricted`, `InsufficientScope`,
1146
- `ContractChanged`, or `CreditCeilingExceeded`. Field validation details remain in `response_data['errors']`,
1147
- an array of `{ 'field' => ..., 'code' => ..., 'message' => ... }`; localized messages are for display, not branching.
1148
-
1149
- ## Tests
255
+ | Error | Raised when |
256
+ | --- | --- |
257
+ | `Assinafy::ValidationError` | input is invalid; raised before any request |
258
+ | `Assinafy::ApiError` | the API refuses; exposes `status_code`, `error_code`, `response_data`, `rate_limit`, `retry_after` |
259
+ | `Assinafy::OAuthError` | an OAuth endpoint refuses (subclass of `ApiError`) |
260
+ | `Assinafy::NetworkError` | connection, timeout or TLS failure |
1150
261
 
1151
- ```bash
1152
- bundle exec rake spec # RSpec, including a coverage matrix
1153
- bundle exec rubocop --cache false # Linting
1154
- bundle exec bundler-audit check --update # Dependency CVEs
1155
- rbs -I sig validate # Published signatures (install rbs outside the bundle)
1156
- ruby scripts/check_api_contract.rb --file path/to/openapi.json # validate a local contract document
1157
- ```
262
+ Branch on `error_code` (for example `PlanRestricted`, `InsufficientScope`, `ContractChanged`,
263
+ `CreditCeilingExceeded`, `FreePlanEmailLimit`), not on the localized message. The SDK never retries; on `429` wait `retry_after`
264
+ seconds.
1158
265
 
1159
- The coverage spec validates the committed route-to-method inventory, public wrappers, aliases, and resource
1160
- mappings without network access. Ordinary pull-request CI remains network-independent; a weekly scheduled job runs
1161
- `scripts/check_api_contract.rb` against the upstream document.
266
+ ## Resources
1162
267
 
1163
- ### Live integration tests
268
+ `client.oauth`, `accounts`, `users`, `documents`, `envelopes`, `contracts`, `signers`,
269
+ `signer_documents`, `assignments`, `scheduled_sends`, `templates`, `tags`, `fields`, `webhooks` and the local
270
+ `webhook_verifier`. The [guide](docs/GUIDE.md#resource-reference) lists the calls for each one.
1164
271
 
1165
- The suite in [`spec/integration/`](spec/integration/live_sandbox_spec.rb) exercises safe sandbox workflows across
1166
- every workspace resource. Signer-code, OTP, password, social-login, API-key mutation, signature upload, and
1167
- irreversible sign/decline calls are wire-contract tested in the default suite but are not live-automated without
1168
- their one-time credentials or explicit state changes. The live suite is excluded from the default run and only
1169
- executes when `ASSINAFY_LIVE=1` is set with credentials:
272
+ ## Development
1170
273
 
1171
274
  ```bash
1172
- ASSINAFY_LIVE=1 \
1173
- ASSINAFY_API_KEY=... \
1174
- ASSINAFY_ACCOUNT_ID=... \
1175
- ASSINAFY_TEST_EMAIL=recipient1@example.com \
1176
- ASSINAFY_TEST_EMAIL2=recipient2@example.com \
1177
- ASSINAFY_TEMPLATE_ID=configured-template-id \
1178
- ASSINAFY_BASE_URL=https://sandbox.assinafy.com.br/v1 \
1179
- bundle exec rspec spec/integration
275
+ bundle exec rspec # unit suite with the route coverage matrix
276
+ bundle exec rubocop --cache false
277
+ bundle exec bundler-audit check --update
278
+ rbs -I sig validate # rbs installed outside the bundle
279
+ ruby scripts/check_api_contract.rb # compares the published OpenAPI with spec/fixtures/api_contract.json
1180
280
  ```
1181
281
 
1182
- `ASSINAFY_TEMPLATE_ID` must identify a sandbox template with a `Signer` role configured in the
1183
- application. Without it, the positive template-generation example is skipped. Supply different test
1184
- recipients for its roles. OAuth browser consent is tested separately with a registered app, an HTTPS
1185
- callback, and the matching authorization server; sandbox keys are not production OAuth credentials.
1186
-
1187
- > These tests create and clean up real resources and, for the assignment flow, send real signature-request emails to the addresses in `ASSINAFY_TEST_EMAIL` / `ASSINAFY_TEST_EMAIL2`.
1188
-
1189
- ## Contributing
1190
-
1191
- Pull requests and issues are welcome at <https://github.com/assinafy/ruby-sdk>.
1192
-
1193
- ## License
282
+ `spec/integration` holds opt-in live tests (`ASSINAFY_LIVE=1` plus credentials). They create and remove real
283
+ resources and send real email to the test recipients you configure.
1194
284
 
1195
- MIT. See [LICENSE](LICENSE).
285
+ Pull requests and issues are welcome at <https://github.com/assinafy/ruby-sdk>. License: [MIT](LICENSE).