assinafy 2.3.0 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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, envelopes, contracts, embedded signing, 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+ (use patched Ruby 4.0.10, 3.4.13 or 3.3.14; 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,1214 +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.
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 |
97
53
 
98
- ### Login, with the two-factor challenge
54
+ User login, passwords, two-factor setup and API-key management stay in the Assinafy app; the SDK does not wrap
55
+ them.
99
56
 
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
- ```
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.
116
61
 
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.
62
+ ## OAuth 2.1 for marketplace apps
121
63
 
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
- ```
139
-
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.
146
-
147
- ### API keys and passwords
148
-
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.
166
-
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' }
94
+ user_client = Assinafy::Client.new(token: tokens.fetch('access_token'), account_id: 'workspace-id')
230
95
  ```
231
96
 
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.
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:
236
101
 
237
102
  ```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)
252
- ```
253
-
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:
258
-
259
- ```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
109
 
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
-
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
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.
340
118
 
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.
119
+ ## Complete signing flow
344
120
 
345
- ### 1. Upload a document and wait for its metadata
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.
346
127
 
347
128
  ```ruby
348
- document = client.documents.upload({ file_path: './customer-agreement.pdf' })
349
- document['name'] # => "customer-agreement.pdf"
129
+ document = client.documents.upload({ file_path: './contract.pdf' })
130
+ document = client.documents.wait_until_ready(document.fetch('id'))
350
131
 
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
- ```
358
-
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.
363
- The high-level `upload_and_request_signatures` helper waits up to 30 seconds by default. For asynchronous
364
- processing, pass `wait_for_ready: false` and poll separately with the required timeout. Its errors retain
365
- the uploaded document and any created signer IDs in `error.context` for recovery without uploading again.
366
-
367
- **Or select a template.** A template upload initially contains an `Editor` role. Configure at least one `Signer`
368
- role and its fields in the Assinafy application before generating a document. Template uploads have the same
369
- 25 MB limit as documents.
370
-
371
- ```ruby
372
- template = client.templates.get('template-id')
373
- ```
374
-
375
- ### 2. Create or reuse signers
376
-
377
- ```ruby
378
132
  signer = client.signers.find_by_email('signer@example.com') ||
379
133
  client.signers.create(full_name: 'Example Signer', email: 'signer@example.com')
380
134
 
381
- # A DigitalCertificate signer needs a CPF or CNPJ in government_id — set it at creation:
382
- cert_signer = client.signers.create(
383
- full_name: 'Certificate Signer',
384
- email: 'cert-signer@example.com',
385
- government_id: ENV.fetch('ASSINAFY_SIGNER_GOVERNMENT_ID')
386
- )
387
- # ...or later: client.signers.update(signer['id'], government_id: '...')
388
- ```
389
-
390
- ### 3. Choose verification and notification methods
391
-
392
- Each assignment signer has a **verification method** (how they prove identity before signing) and a
393
- **notification method** (how they receive the invitation). The two are **coupled**: send one, both, or neither —
394
- the missing side is inferred from the other, and when both are omitted both default to `Email`.
395
-
396
- | Verification | How it works | Allowed notification | Cost per signer |
397
- | --- | --- | --- | --- |
398
- | `Email` *(default)* | One-time code (OTP) by email before signing | `Email` | 0 credits |
399
- | `Whatsapp` | One-time code (OTP) over WhatsApp; needs `whatsapp_phone_number` and a paid plan | `Whatsapp` | 0.45 credits (the WhatsApp notification) |
400
- | `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) |
401
- | `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 |
402
-
403
- - Send exactly one channel in `notification_methods` (a one-element array).
404
- - The certificate charge appears in the cost breakdown under the code `SignatureDigitalCertificate`. Resending a
405
- notification charges the notification again.
406
- - `DigitalCertificate` needs the Digital Certificate account feature (Standard and Pro plans), a CPF or CNPJ in the
407
- signer's `government_id`, a `method: 'virtual'` assignment, and the signer alone in its signing step. A collect
408
- assignment, including one inferred from a template with positioned signer fields, cannot use certificate
409
- signing. Direct assignment creation and estimation reject it with `ValidationError` code
410
- `digital_certificate_requires_virtual`. A CPF requires that person's certificate (an e-CPF, or an e-CNPJ naming
411
- them as legal representative); a CNPJ requires an e-CNPJ for that company, from any of its representatives.
412
- - `AssignmentResource::VERIFICATION_METHODS` and `::NOTIFICATION_METHODS` publish the enums. `build_payload`
413
- validates values, pairings, and `step` locally, so a typo fails before the request is sent.
414
-
415
- ### 4. Estimate the cost
416
-
417
- ```ruby
418
- estimate = client.assignments.estimate_cost(
419
- document.fetch('id'),
420
- signers: [
421
- { verification_method: 'Email' },
422
- { verification_method: 'DigitalCertificate', notification_methods: ['Whatsapp'] }
423
- ]
424
- )
425
- estimate['total_credits'] # => 0.95
426
- estimate['breakdown'] # [{ 'code' => ..., 'quantity' => ..., 'unit_cost' => ..., 'cost' => ... }]
427
- estimate['has_sufficient_resources'] # => true
428
- ```
429
-
430
- Estimates accept signers described by method alone, without an `id`.
431
-
432
- ### 5. Create the assignment
433
-
434
- ```ruby
435
- assignment = client.assignments.create(
436
- document.fetch('id'),
437
- method: 'virtual',
438
- signers: [
439
- { id: signer.fetch('id'), verification_method: 'Email', notification_methods: ['Email'], step: 1 },
440
- { id: cert_signer.fetch('id'), verification_method: 'DigitalCertificate', notification_methods: ['Email'], step: 2 }
441
- ],
442
- message: 'Please review and sign.',
443
- expires_at: '2099-12-31T23:59:00Z'
444
- )
445
- assignment['signing_urls'] # => [{ 'signer_id' => 'signer-id', 'url' => 'https://.../sign/...' }, ...]
446
- ```
447
-
448
- `virtual` has no positioned fields and is required for `DigitalCertificate`; `collect` adds `entries` of
449
- positioned fields (see [Assignments](#assignments)). Both require a non-empty `signers` array. Steps are
450
- all-or-none, positive, and contiguous from 1; equal steps sign in parallel, and each step is notified when the
451
- previous one finishes. A certificate signer is alone in its step. Deadlines are zoned ISO 8601 and at least one
452
- hour ahead.
453
-
454
- For a template, bind one distinct signer to each role; processing creates the document's assignment:
455
-
456
- ```ruby
457
- role_signer = {
458
- role_id: template.fetch('roles').find { |role| role['assignment_type'] == 'Signer' }.fetch('id'),
459
- id: signer.fetch('id'),
460
- verification_method: 'Email',
461
- 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
462
141
  }
463
142
 
464
- client.documents.estimate_cost_from_template(template.fetch('id'), [role_signer])
465
- template_document = client.documents.create_from_template(
466
- template.fetch('id'), [role_signer],
467
- name: 'customer-agreement.pdf', message: 'Please review and sign.',
468
- idempotency_key: 'template-request-id'
469
- )
470
- # Initial response: status "uploaded", assignment nil; processing creates the assignment afterward.
471
- # Follow document status/webhooks until pending_signature or failed.
472
- # wait_until_ready waits for metadata and can return before the template assignment exists.
473
- ```
474
-
475
- Template creation also accepts `email` and `name` for a role instead of an existing signer `id`; the server reuses
476
- or creates the signer. Keep the same `idempotency_key` after a lost response to avoid duplicate documents and
477
- charges. `max_total_credits` can cap creation costs; a higher actual price returns `409` with
478
- `error_code == 'CreditCeilingExceeded'`, creating and charging nothing.
479
-
480
- **Shortcut.** `Client#upload_and_request_signatures` bundles upload, waiting, signer creation (including
481
- `government_id`), and a virtual assignment, validating the whole payload before anything is uploaded:
482
-
483
- ```ruby
484
- result = client.upload_and_request_signatures(
485
- source: { file_path: './contract.pdf' },
486
- signers: [{ full_name: 'Alice Silva', email: 'alice@example.com' }],
487
- message: 'Please sign.',
488
- expires_at: '2099-12-31T23:59:00Z'
489
- )
490
- result[:document]['id'] # => "document-id"
491
- result[:signer_ids] # => ["signer-id"]
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/...' }]
492
146
  ```
493
147
 
494
- It is not transactional: on a later failure, `e.context[:document]` and `e.context[:signer_ids]` list what was
495
- created so you can clean up.
496
-
497
- ### 6. The signer experience
498
-
499
- The signer receives an access link through the notification channel. Signer-facing calls use
500
- `signer-access-code` as a query parameter, with workspace credentials removed. The code remains usable during
501
- signing and closes 30 minutes after that signer is done; an envelope code closes after all their documents are
502
- done. After closure, document reads return only signer status, theme/logo and certified-copy delivery remain
503
- available, and other signer calls return `410`.
504
-
505
- ```ruby
506
- signing = Assinafy::Client.new(base_url: ENV.fetch('ASSINAFY_BASE_URL'))
507
- access_code = ENV.fetch('ASSINAFY_SIGNER_ACCESS_CODE')
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.
508
151
 
509
- signer_data = signing.signers.self_data(signer_access_code: access_code)
510
- signing.signers.accept_terms(signer_access_code: access_code) unless signer_data['has_accepted_terms']
152
+ ### Verification and notification methods
511
153
 
512
- signing_document = signing.assignments.signer_document(signer_access_code: access_code, has_accepted_terms: true)
513
- signing.signers.confirm_data(
514
- signing_document.fetch('id'), { email: 'signer@example.com', has_accepted_terms: true },
515
- signer_access_code: access_code
516
- )
517
- signing.signers.verify_email( # the OTP from email or WhatsApp
518
- verification_code: ENV.fetch('ASSINAFY_VERIFICATION_CODE'),
519
- signer_access_code: access_code
520
- )
521
- signing.signers.upload_signature(File.binread('signature.png'), signer_access_code: access_code, type: 'signature')
522
-
523
- signing.assignments.sign(
524
- signing_document.fetch('id'), signing_document.dig('assignment', 'id'), [], signer_access_code: access_code
525
- )
526
- # sign_multiple is also available for batches of virtual documents.
527
- ```
528
-
529
- That signs a virtual assignment. For a collect assignment, upload both the signature and initial images, then
530
- submit required item values through `assignments.sign`. This example places only signature fields; add values
531
- matching each field's type for other editable fields. Omit read-only dates, which the server fills:
532
-
533
- ```ruby
534
- signing.signers.upload_signature(File.binread('initial.png'), signer_access_code: access_code, type: 'initial')
535
- items = signing_document.fetch('assignment').fetch('items')
536
- collect_items = items.select { |item| item.dig('field', 'type') == 'signature' }.map do |item|
537
- { item_id: item.fetch('id'), field_id: item.dig('field', 'id'), page_id: item.dig('page', 'id'), value: 'Accepted' }
538
- end
539
-
540
- signing.assignments.sign(
541
- signing_document.fetch('id'), signing_document.dig('assignment', 'id'), collect_items,
542
- signer_access_code: access_code
543
- )
544
-
545
- # To decline instead:
546
- signing.assignments.decline(
547
- signing_document.fetch('id'), signing_document.dig('assignment', 'id'),
548
- decline_reason: 'Terms differ from the proposal', signer_access_code: access_code
549
- )
550
- ```
551
-
552
- **Biometric signers** use `verification_method: 'IdDocumentFaceMatchBasic'` with exactly one Email or Whatsapp
553
- notification in virtual/collect assignments or template generation. Store a valid CPF in the signer's
554
- `government_id` first and call `estimate_cost` or `estimate_cost_from_template` for the current price.
555
- The OTP example above applies to Email/Whatsapp. For biometrics, read the verification state and collect explicit
556
- biometric-processing consent before starting:
557
-
558
- ```ruby
559
- state = signing.signers.identity_verification(signer_access_code: access_code)
560
- # => { 'can_start' => true, 'status' => nil, 'url' => nil, 'expires_at' => nil, 'completed_at' => nil }
561
-
562
- # After the signer explicitly consents to biometric processing:
563
- session = signing.signers.start_identity_verification(consent: true, signer_access_code: access_code)
564
- # => { 'id' => 'verification-id', 'url' => 'https://verify.assinafy.com.br/c/session#t=token-placeholder',
565
- # 'expires_at' => '2026-10-16T13:00:00Z' }
566
- ```
567
-
568
- Open the capture URL unchanged, including its `#t=` fragment. It is a bearer link: keep it out of logs and browser
569
- storage. For an existing Pending session, use the URL from `identity_verification`. `can_start` is true only
570
- before any session or after Expired; restarting an Expired session costs nothing extra. Declined or Abandoned
571
- requires a new document and assignment.
572
-
573
- InReview lets the signer view, confirm data and sign while account review holds certification. After all signers
574
- sign, the document can be `pending_identity_review`. The account reviewer uses an API key or user session:
575
-
576
- ```ruby
577
- review = client.assignments.identity_review(document.fetch('id'), assignment.fetch('id'), signer.fetch('id'))
578
- # => SignerIdentityReview: status, reason_codes, evidence_available, expected, document, matches,
579
- # checks, images, ruleset_version, evidence_sha256 and decision metadata
580
- image = client.assignments.identity_review_image(document.fetch('id'), assignment.fetch('id'), signer.fetch('id'), 'face')
581
- # => JPEG, PNG or PDF bytes, depending on the name listed in review['images']; do not cache
582
-
583
- # After the reviewer checks the evidence:
584
- client.assignments.decide_identity_review(
585
- document.fetch('id'), assignment.fetch('id'), signer.fetch('id'), decision: 'Approved', note: 'Identity checked'
586
- )
587
- ```
588
-
589
- `decision: 'Rejected'` cancels the document and notifies signers and copy receivers. The optional note accepts at
590
- most 2000 characters, goes to activities and the provider, and is never shown to the signer. Images exist only
591
- during InReview. Observe signer_identity_review_required, signer_identity_review_approved,
592
- signer_identity_review_rejected, signer_identity_verified and signer_identity_verification_failed events.
593
- Third-party OAuth apps can read the review summary with `documents:read`; they cannot fetch evidence images or
594
- submit the human review decision. For envelopes, one biometric check covers the signer's documents; rejection
595
- cancels the whole envelope and notifies each recipient once.
596
-
597
- **A1/A3 certificate signers** complete their signature in Assinafy's hosted signing flow, opened from
598
- `assignment['signing_urls']`: they accept the terms, confirm their data, and sign with their A1 or A3 certificate
599
- through the Web PKI browser extension. The ordinary signing endpoint rejects certificate signers, and the SDK does
600
- not wrap the Web PKI handshake (`/signers/certificate/start`, `/signers/certificate/complete`), whose schemas are
601
- not part of the OpenAPI contract. Once it completes, the `pades` artifact returns the qualified signature.
602
-
603
- ### 7. Receive webhooks
604
-
605
- An account can have 1 webhook endpoint, or up to 3 on paid plans. Each has its own distinct URL, event list, and
606
- signing setting, and every active endpoint subscribed to an event receives it.
607
-
608
- ```ruby
609
- client.webhooks.list_event_types # => [{ 'id' => 'document_ready', 'description' => '...' }, ...]
610
-
611
- endpoint = client.webhooks.create_endpoint(
612
- url: 'https://app.example.com/webhooks/assinafy',
613
- email: 'ops@example.com', # delivery-failure notices
614
- events: %w[document_ready signer_signed_document signer_rejected_document],
615
- name: 'ERP',
616
- signing_enabled: true
617
- )
618
- secret = endpoint.fetch('secret') # returned once on creation; store it immediately, including for OAuth apps
619
- ```
620
-
621
- - `create_endpoint` requires `url`, `email`, and `events`; `name`, `is_active` (default `true`), and
622
- `signing_enabled` (default `false`) are optional. Unknown keys raise `ValidationError` locally.
623
- - Creating one past the plan limit answers `403`; a URL another endpoint already uses answers `400`.
624
- - `update_endpoint(id, payload)` changes only the fields sent. `signing_enabled: true` creates a secret when the
625
- endpoint has none and keeps the current one otherwise; `false` discards it.
626
- - `rotate_endpoint_secret(id)` returns a new secret; the old one stops working immediately. Pass
627
- `keep_previous: true` for 24 hours of signatures from both secrets while receivers switch.
628
- - Reading a secret requires an API key or user session. Rotation is available to OAuth apps with
629
- `webhooks:write`, including recovery of a lost secret. Both methods answer `400` when signing is disabled.
630
- - Enabling signing with `update_endpoint` returns the new secret once. Store it before using the endpoint.
631
- - `list_endpoints(url: registered_url)` filters by exact URL; `delete_endpoint_by_url(registered_url)` removes
632
- that endpoint and returns `nil` (`404` when no endpoint matches).
633
-
634
- **Delivery contract.** Each delivery is a `POST` with an `application/json` body and the headers `webhook-id`
635
- (identical on every attempt of the same event to the same endpoint — deduplicate on it), `webhook-timestamp`
636
- (Unix seconds), and, when signing is enabled, `webhook-signature`. Any `2xx` is success. Network failures,
637
- timeouts, `408`, `429` and `5xx` get up to six attempts about ten minutes apart; other statuses are final.
638
- After ten failed deliveries in a row the endpoint pauses. Probes follow after 3, 15 and 60 minutes, then every
639
- six hours; success releases queued events oldest first. Updating its URL or setting `is_active: true` also lifts
640
- the pause. `retry_dispatch` sends now; `test_endpoint` sends a separate `webhook_test` without changing the pause.
641
- Delivery history is retained for seven days and captures the first 2000 response-body characters.
642
-
643
- **Verifying signatures.** Signatures follow [Standard Webhooks](https://www.standardwebhooks.com): space-separated
644
- `v1,<base64 HMAC-SHA256>` entries over `"{webhook-id}.{webhook-timestamp}.{raw body}"`, keyed with the
645
- base64-decoded part of the secret after `whsec_`. `verify_delivery` checks them in constant time and rejects
646
- timestamps more than 5 minutes from the local clock (`tolerance:` changes the window):
647
-
648
- ```ruby
649
- class AssinafyWebhooksController < ActionController::API
650
- VERIFIER = Assinafy::Support::WebhookVerifier.new(ENV.fetch('ASSINAFY_WEBHOOK_SECRET'))
651
-
652
- def create
653
- raw_body = request.raw_post
654
- return head(:unauthorized) unless VERIFIER.verify_delivery(raw_body, request.headers)
655
-
656
- webhook_id = request.headers['webhook-id']
657
- return head(:ok) if AssinafyEvent.exists?(webhook_id: webhook_id) # already processed
658
-
659
- event = VERIFIER.extract_event(raw_body)
660
- AssinafyEvent.create!(webhook_id: webhook_id, kind: VERIFIER.event_type(event), body: raw_body)
661
- ProcessAssinafyEventJob.perform_later(webhook_id)
662
- head :ok
663
- end
664
- end
665
- ```
666
-
667
- In plain Rack (Sinatra, Roda), pass the env: `VERIFIER.verify_delivery(request.body.read, request.env)` — the
668
- `HTTP_WEBHOOK_ID` form is accepted, as is a plain Hash. `verify_delivery` returns `false` — never raises — for a
669
- missing or malformed secret, a missing header, a wrong signature, or a stale timestamp. Always pass the **raw**
670
- body exactly as received. `client.webhook_verifier` is a verifier built from the client's `webhook_secret`.
671
-
672
- `extract_event` parses the body (or returns `nil`); `event_type`, `event_payload`, `event_object` (the entity acted
673
- on), and `event_subject` (the actor) read the envelope `{ id, event, message, payload, origin, created_at,
674
- subject, object, account_id }`. `subject` and `object` carry a `type` (`User`, `Signer`, `Account`, `Document`, or
675
- `Template`); body timestamps are Unix seconds.
676
-
677
- `verify(raw_body, hex_signature)` remains only for receivers whose own gateway signs bodies with a hex
678
- HMAC-SHA256 shared secret.
679
-
680
- Give the webhook event table a unique index on `webhook_id`, process events idempotently, and arrange durable
681
- job delivery before acknowledging the request so concurrent retries or a failed enqueue cannot lose an event.
682
-
683
- ### 8. Track progress, download, and verify
684
-
685
- ```ruby
686
- document_id = document.fetch('id')
687
-
688
- client.documents.signing_progress(document_id) # => { signed: 1, total: 2, pending: 1, percentage: 50.0 }
689
- client.documents.fully_signed?(document_id)
690
- client.documents.activities(document_id) # => one page of Array<DocumentActivity>
691
- client.documents.activities_page(document_id, page: 1, per_page: 20) # => { data:, meta: }
692
-
693
- signed_pdf = client.documents.download(document_id, 'certificated')
694
- # also 'original', 'certificate-page', 'bundle' (zip), and 'pades' for certificate-signed documents
695
-
696
- verification = client.documents.verify('signature-hash-from-assinafy')
697
- verification['is_valid'] # => true
698
- verification['agreement_code'] # printed on the document certificate
699
- ```
700
-
701
- `verify` returns Assinafy's verification result. It does not independently validate the PDF signature or its
702
- certificate chain; see [Authentication and safety](docs/API_REFERENCE.md#authentication-and-safety).
703
-
704
- ### 9. Clean up
705
-
706
- ```ruby
707
- client.documents.delete(document_id)
708
- client.signers.delete(signer.fetch('id'))
709
- client.webhooks.delete_endpoint(endpoint.fetch('id'))
710
- ```
711
-
712
- Delete only resources your application owns, after downstream work is complete; keep shared signer and template
713
- data. Some resources return `409` while processing or while still referenced.
714
-
715
- ### 10. Handle errors
716
-
717
- ```ruby
718
- begin
719
- client.documents.details(document_id)
720
- rescue Assinafy::ValidationError => e
721
- warn e.errors.inspect
722
- rescue Assinafy::ApiError => e
723
- warn "Assinafy returned #{e.status_code}: #{e.message}"
724
- sleep(e.retry_after) if e.status_code == 429 && e.retry_after # also e.rate_limit => { limit:, remaining:, reset: }
725
- rescue Assinafy::NetworkError => e
726
- warn "Network failure: #{e.message}"
727
- end
728
- ```
729
-
730
- See [Errors](#errors) for the full hierarchy.
731
-
732
- ## Resource reference
733
-
734
- `Assinafy::Client` exposes the API resources below plus the local `webhook_verifier` helper:
735
-
736
- | Accessor | What it covers |
737
- | --------------------------- | ------------------------------------------------------------------ |
738
- | `client.auth` | Login, two-factor authentication, social login, passwords, API keys |
739
- | `client.oauth` | OAuth 2.1 token exchange, refresh, revocation, userinfo, discovery |
740
- | `client.accounts` | Account CRUD, theme, KPI stats, brand logo |
741
- | `client.users` | User profile, notification preferences, cross-account KPIs |
742
- | `client.documents` | Upload, list, search, rename, download, delete, verify, tags |
743
- | `client.envelopes` | Send several documents together, estimate, reorder, cancel and download |
744
- | `client.contracts` | Contract terms, amendments, renewals, terminations |
745
- | `client.signers` | Workspace signer CRUD + signer self-service endpoints |
746
- | `client.signer_documents` | Signer-authenticated multi-document operations + search |
747
- | `client.assignments` | List/create/sign/decline/resend/estimate assignments |
748
- | `client.templates` | Template creation (file upload), get, list, update, delete |
749
- | `client.tags` | Workspace tags |
750
- | `client.fields` | Field definitions + validation + type catalog |
751
- | `client.webhooks` | Webhook endpoints, signing secrets, event catalog, deliveries, retries |
752
- | `client.webhook_verifier` | Standard Webhooks signature verification for received deliveries |
753
-
754
- ### Accounts
755
-
756
- ```ruby
757
- client.accounts.list # { data: [...] } — no pagination meta
758
- client.accounts.get # the current account (or pass an id)
759
- client.accounts.get(expand: 'signing_features') # includes available signing features
760
- client.accounts.create(name: 'Acme Inc.')
761
- client.accounts.update({ name: 'Acme Renamed' })
762
- client.accounts.delete(force: true, account_id_override: 'account-id')
763
- client.accounts.theme # { account_name, primary_color, secondary_color, logo }
764
- client.accounts.stats(granularity: 'monthly', month: '2026-06') # account KPI rows
765
- client.accounts.upload_logo({ file_path: './logo.png' })
766
- client.accounts.download_logo # raw bytes; raises ApiError on HTTP 404 when unset
767
- client.accounts.delete_logo
768
- client.accounts.usage # { 'plan' => ..., 'documents_renewal_date' => ..., 'balances' => { ... } }
769
- client.accounts.notification_policy # { 'editable' => true, 'owners_receive_all' => false, 'events' => { ... } }
770
- client.accounts.update_notification_policy(events: { SignerViewed: false }, owners_receive_all: true)
771
- ```
772
-
773
- Usage and notification policy are unavailable to third-party OAuth applications. Policy writes require an owner;
774
- they merge only supplied event flags. A disabled workspace event suppresses it across channels even when a
775
- member enables it. `SignerIdentityReviewRequired: false` disables only push; its email is always sent.
776
-
777
- ### Users
778
-
779
- ```ruby
780
- client.users.me
781
- client.users.stats(granularity: 'daily', month: '2026-06') # cross-account KPI rows
782
- client.users.notification_preferences # returns all thirteen owner-email preferences
783
- client.users.update_notification_preferences(SignerDeclined: false) # partial request; returns all thirteen
784
- client.users.push_preferences # eight phone-push preferences; separate from email
785
- client.users.update_push_preferences(SignerViewed: false) # partial request; returns the full push map
786
- ```
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 |
787
160
 
788
- Email and push preferences apply to the user across workspaces. They accept boolean values and reject unknown
789
- 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.
790
165
 
791
- Both stats methods validate `granularity` (`monthly` or `daily`) and `month` (`YYYY-MM`) locally; daily statistics
792
- require `month`. They return rows
793
- with `period`, `documents_uploaded`, `documents_sent`, `signature_requests`,
794
- `signature_requests_notification_email`, `signature_requests_notification_whatsapp`,
795
- `signature_requests_notification_bypass`, `signature_requests_verification_email`,
796
- `signature_requests_verification_whatsapp`, `signature_requests_verification_bypass`,
797
- `signature_requests_verification_digital_certificate`, `signature_requests_viewed`,
798
- `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.
799
175
 
800
- ### Documents
176
+ ### Templates, envelopes and scheduled sends
801
177
 
802
178
  ```ruby
803
- client.documents.statuses # GET /documents/statuses
804
- client.documents.list(page: 1, per_page: 20, status: 'pending_signature')
805
- client.documents.list(tags: ['tag-id-1', 'tag-id-2']) # documents carrying every listed tag
806
- client.documents.list(envelope_id: 'envelope-id') # documents in an envelope
807
- client.documents.search('contract') # lightweight GET .../documents/search
808
- client.documents.upload({ file_path: './contract.pdf' }) # named after the file
809
- client.documents.upload({ buffer: pdf_bytes, file_name: 'contract.pdf' })
810
- client.documents.rename('document-id', 'renamed.pdf') # PATCH /documents/{id}
811
- client.documents.get('document-id') # alias of .details
812
- client.documents.details('document-id', expand: ['envelope_id', 'envelope'])
813
- client.documents.wait_until_ready('document-id', max_wait_seconds: 60)
814
- client.documents.activities('document-id')
815
- client.documents.activities_page('document-id', sort: '-id', page: 1, per_page: 20)
816
- client.documents.thumbnail('document-id') # binary PNG/JPEG
817
- client.documents.thumbnail('document-id', artifact: 'certificated') # rendered signed content
818
- client.documents.download('document-id', 'certificated') # binary PDF
819
- client.documents.download('document-id', 'pades') # signed PAdES artifact
820
- client.documents.download_page('document-id', 'page-id')
821
- client.documents.download_page('document-id', 'page-id', artifact: 'certificated')
822
- client.documents.delete('document-id')
823
- client.documents.verify('signature-hash')
824
- client.documents.public_info('document-id')
825
- client.documents.send_token('document-id', recipient: 'signer@example.com')
826
- client.documents.list_tags('document-id')
827
- client.documents.replace_tags('document-id', ['tag-id-1', 'tag-id-2'])
828
- client.documents.append_tags('document-id', ['tag-id-3'])
829
- client.documents.detach_tag('document-id', 'tag-id')
830
-
831
- client.documents.create_from_template(
832
- 'template-id',
833
- [{ role_id: 'role-id', id: 'signer-id', verification_method: 'Email', notification_methods: ['Email'] }],
834
- { name: 'Contract', message: 'Please sign', expires_at: '2099-12-31T23:59:00Z' }
835
- )
836
- client.documents.estimate_cost_from_template('template-id', [{ role_id: 'role-id', verification_method: 'Whatsapp' }])
837
-
838
- client.documents.fully_signed?('document-id')
839
- client.documents.signing_progress('document-id') # => { signed: 1, total: 2, pending: 1, percentage: 50.0 }
840
- ```
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
- An Array `tags` filter is sent as comma-separated tag IDs. The tag arrays of `replace_tags`/`append_tags` take tag
843
- IDs.
844
-
845
- Activities default to twenty per page. `activities` preserves the Array return; `activities_page` exposes the
846
- pagination headers so callers can traverse every event. Signed thumbnails/pages use `artifact: 'certificated'`
847
- with workspace credentials. The first render can wait up to thirty seconds, then return `503` with `Retry-After`;
848
- the SDK does not retry. These renders carry `Cache-Control: no-store`. Certificate pages have no document page
849
- IDs, and the qualified certificate seal is available in the `pades` artifact.
850
-
851
- ### Envelopes
852
-
853
- Send up to 20 prepared documents to up to 20 existing signers in one invitation. Each document retains its own
854
- assignment, status and artifacts. All envelope signers sign in parallel; no `step` is accepted.
855
-
856
- ```ruby
857
- request = {
858
- name: 'Agreement and annex',
859
- signers: [{ id: 'signer-id', verification_method: 'Email', notification_methods: ['Email'] }],
860
- documents: [
861
- { id: 'agreement-id', signer_ids: ['signer-id'] },
862
- { id: 'annex-id', signer_ids: ['signer-id'] }
863
- ]
864
- }
865
- estimate = client.envelopes.estimate_cost(request)
866
182
  envelope = client.envelopes.create(
867
- request.merge(max_total_credits: estimate.fetch('total_credits')), idempotency_key: 'envelope-request-id'
868
- )
869
- # => { 'id' => 'envelope-id', 'name' => 'Agreement and annex', 'message' => nil,
870
- # 'documents' => [...], 'counts' => { 'pending_signature' => 2 },
871
- # 'signing_urls' => [...], 'created_at' => '2026-11-11T12:00:00Z' }
872
-
873
- client.envelopes.list(status: 'open') # { data: [...], meta: { ... } }
874
- client.envelopes.get(envelope.fetch('id'))
875
- client.envelopes.update(envelope.fetch('id'), document_ids: %w[annex-id agreement-id], message: nil)
876
- client.envelopes.activities(envelope.fetch('id')) # paginated events with document_id/document_name
877
- client.envelopes.resend_notification(envelope.fetch('id'), 'signer-id') # { 'is_sent' => true, ... }
878
- client.envelopes.add_document(envelope.fetch('id'), id: 'extra-document-id', signer_ids: ['signer-id'])
879
- client.envelopes.remove_document(envelope.fetch('id'), 'extra-document-id') # cancels and removes that open document
880
- archive = client.envelopes.download(envelope.fetch('id'), 'original') # ZIP bytes in envelope order
881
- client.envelopes.cancel(envelope.fetch('id')) # [{ 'id' => ..., 'status' => ..., 'cancelled' => true }]
882
- client.envelopes.delete(envelope.fetch('id')) # nil; closed envelopes only, documents remain
883
- ```
884
-
885
- `collect` documents add positioned `entries` whose field signers exactly match `signer_ids`. Every envelope
886
- signer must appear on a document. A certificate signer signs alone on each virtual document and is charged per
887
- document; a biometric signer verifies once for the envelope. Preserve the creation idempotency key after an
888
- ambiguous response. `max_total_credits` prevents creating or charging an envelope above the approved cost.
889
-
890
- ### Scheduled sends and document recipients (staging)
891
-
892
- These calls are published on `https://api.angry-pisco.stage.assinafy.com.br/v1`, ahead of production.
893
- Use the matching staging credentials and base URL. Production may return 404 until these routes are deployed.
894
-
895
- ```ruby
896
- scheduled = client.assignments.schedule(
897
- 'document-id', { signers: [{ id: 'signer-id', sign_as: 'Witness' }], max_total_credits: 1 },
898
- send_at: (Time.now + 7200).iso8601
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'
899
187
  )
900
- # => { 'id' => 'send-id', 'type' => 'assignment', 'document_ids' => ['document-id'],
901
- # 'status' => 'pending', 'send_at' => '2026-12-01T12:00:00Z', 'assignment_id' => nil,
902
- # 'envelope_id' => nil, 'failure_reason' => nil, 'created_at' => '2026-12-01T10:00:00Z',
903
- # 'processed_at' => nil }
904
- client.scheduled_sends.list(document_id: 'document-id', per_page: 20) # { data:, meta: }
905
- client.scheduled_sends.cancel(scheduled.fetch('id')) # status: cancelled; no charge
906
- # Or send a pending request immediately:
907
- # client.scheduled_sends.send_now(scheduled.fetch('id')) # status: sent; assignment_id/envelope_id populated
908
-
909
- client.envelopes.schedule(
910
- { name: 'Contract', signers: [{ id: 'signer-id' }],
911
- documents: [{ id: 'another-document-id', signer_ids: ['signer-id'] }] },
912
- send_at: (Time.now + 7200).to_i
913
- ) # ScheduledSend with type: envelope
914
-
915
- client.documents.signer_capacities('document-id') # [{ 'signer_id' => 'signer-id', 'sign_as' => 'Witness' }]
916
- client.documents.set_watchers('document-id', ['contact-id']) # Array<Signer>; [] clears all
917
- client.documents.watchers('document-id') # Array<Signer>
918
- client.documents.notification_history('document-id') # signer_id plus records with delivered_at/opened_at
919
- client.envelopes.estimate_resend_cost('envelope-id', 'signer-id') # total, breakdown, credit_balance, has_sufficient_credits
920
- ```
921
188
 
922
- Scheduling creates no assignment, invitation or charge until delivery. `send_at` accepts Unix seconds or
923
- ISO 8601 (no offset means UTC), one hour to 90 days ahead. Each document's deadline must be at least two hours
924
- later. All schedule operations, including listing, need OAuth `documents:write`. Delivery uses the original
925
- member's permissions and then-current balance, plan and price; preserve `max_total_credits` to bound charges.
926
- The worker checks about every five minutes. A failed send records a reason and notifies the original member
927
- (or active owners if they left). Send-now failures leave the request pending; cancel it to prevent a later attempt.
928
- Only pending sends can be cancelled or sent now. Scheduling does not accept idempotency keys.
929
-
930
- `sign_as` defaults to `Sign`; other exact values are in `AssignmentResource::SIGNER_CAPACITIES`. It records
931
- the sender's statement on the certificate and is read separately, not from ordinary assignments or webhooks.
932
- Watchers are up to ten workspace contacts with email, editable until the document ends. They receive a terminal
933
- status email without a document link/file, independently of workspace notification policy. Delivery/open times
934
- are nullable; an open is a hint, not proof a human read the invitation. Reminder estimates do not check eligibility;
935
- staging limits reminders to one per two minutes and ten per 24 hours, shared across an envelope's documents.
936
-
937
- ### Embedded signing
938
-
939
- Requires the account's Embed feature and an API key or user session; third-party OAuth cannot create sessions.
940
- Register exact allowed origins, then mark the signer `embedded: true` with Email or Whatsapp verification:
941
-
942
- ```ruby
943
- origin = client.accounts.create_embed_origin('https://app.example.com')
944
- # => { 'id' => 'origin-id', 'origin' => 'https://app.example.com', 'created_at' => '2026-11-11T12:00:00Z' }
945
- client.accounts.list_embed_origins
946
- client.accounts.update_embed_origin(origin.fetch('id'), 'https://sign.example.com')
947
-
948
- assignment = client.assignments.create(
949
- 'document-id', method: 'virtual',
950
- signers: [{ id: 'signer-id', verification_method: 'Email', notification_methods: ['Email'], embedded: true }]
951
- )
952
- session = client.assignments.create_embed_session('document-id', assignment.fetch('id'), 'signer-id')
953
- # => { 'url' => 'https://app.assinafy.com.br/embed/session-token', 'expires_at' => '2026-11-11T12:05:00Z' }
954
- # Pass session['url'] only to the intended signer's page and load it in an iframe.
955
- client.accounts.delete_embed_origin(origin.fetch('id')) # nil; removes that embedding permission
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)
956
191
  ```
957
192
 
958
- Origins have no path, query, fragment or wildcard; HTTPS is required except HTTP localhost/127.0.0.1.
959
- At most ten origins are allowed. Mint a fresh single-use URL for each frame display; it expires after five
960
- minutes. `signing_urls` contains `url: nil, embedded: true` for embedded signers; invitations still deliver their
961
- code. Follow the live [Embedded Signing Guide](https://api.assinafy.com.br/v1/docs) for the `assinafy:hello`
962
- handshake and validate both `postMessage` origin and iframe window. Confirm completion through a webhook or
963
- document read; frame events alone do not authorize application actions.
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`.
964
197
 
965
- `assignments.exchange_embed_session(token, parent_origin:)` is the token-only operation used by the Assinafy
966
- embed page. An ordinary integration loads the session URL; it does not exchange the token itself or expose the
967
- returned signer access code. Resend the code through `assignments.resend_notification` from your backend.
968
-
969
- ### Contracts
970
-
971
- ```ruby
972
- contract = client.contracts.update(
973
- 'document-id',
974
- status: 'active', counterparty_name: 'Example Ltda', value: 120_000, currency: 'BRL',
975
- start_date: '2026-11-01', end_date: '2027-10-31', auto_renew: true,
976
- renewal_term_months: 12, notice_period_days: 30
977
- )
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.
978
200
 
979
- client.contracts.get('document-id')
980
- client.contracts.list(status: ['active'], ending_within_days: 30)
981
- client.contracts.related('document-id')
982
- client.contracts.related('document-id', expand: 'document') # also includes the parent document
983
- client.contracts.renew('document-id', term: contract['term'], updated_at: contract['updated_at'])
984
- client.contracts.terminate('document-id', reason: 'Ended by the parties')
985
- ```
986
-
987
- `update` is partial and preserves explicit `nil` values as JSON `null`. Link an amendment document with
988
- `parent_document_id` and `relation_type`. Reads require OAuth scope `documents:read`; writes require
989
- `documents:write` and a plan with contract tracking. `get` and `related` return `nil` when no tracked terms exist.
990
-
991
- ### Signers (workspace CRUD)
992
-
993
- ```ruby
994
- client.signers.create(full_name: 'Alice Silva', email: 'alice@example.com')
995
- client.signers.create(full_name: 'Bob Costa', phone: '+5500000000000') # phone -> whatsapp_phone_number
996
- client.signers.create(full_name: 'Carla Lima', email: 'carla@example.com', government_id: '00000000000')
997
- client.signers.validate_create!(full_name: 'Alice Silva', email: 'alice@example.com') # no request
998
- client.signers.get('signer-id')
999
- client.signers.list(search: 'alice', per_page: 50) # returns { data:, meta: }
1000
- client.signers.update('signer-id', full_name: 'Alice S.', government_id: '00000000000')
1001
- client.signers.delete('signer-id')
1002
- client.signers.find_by_email('alice@example.com') # case-insensitive; nil when no match
1003
- ```
1004
-
1005
- `signers.update` changes only supplied fields. Explicit `nil` or `''` clears email, WhatsApp number or
1006
- government ID; full_name cannot be cleared. Verified channels on unfinished requests cannot change, and changing
1007
- an unverified channel invalidates old invitation links. `confirm_data` only reads email, WhatsApp number and terms;
1008
- name/government-ID changes belong in workspace signer updates.
201
+ ### Embedded signing
1009
202
 
1010
- ### 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:
1011
206
 
1012
207
  ```ruby
1013
- client.signers.self_data(signer_access_code: 'code') # includes has_signature, has_initial, is_signature_reusable
1014
- client.signers.accept_terms(signer_access_code: 'code')
1015
- client.signers.verify_email(verification_code: '123456', signer_access_code: 'code')
1016
- client.signers.confirm_data('document-id', { email: 'alice@example.com', has_accepted_terms: true }, signer_access_code: 'code')
1017
- client.signers.upload_signature(png_bytes, signer_access_code: 'code', type: 'signature', content_type: 'image/png')
1018
- client.signers.download_signature(signer_access_code: 'code', type: 'signature')
1019
- client.signers.theme(signer_access_code: 'code') # account_name, primary_color, secondary_color, logo
1020
- 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
1021
210
  ```
1022
211
 
1023
- ### Assignments
212
+ ### Webhooks
1024
213
 
1025
214
  ```ruby
1026
- # Virtual (no positioned fields)
1027
- client.assignments.create(
1028
- 'document-id',
1029
- method: 'virtual',
1030
- signers: [{ id: 'signer-1', verification_method: 'Email', notification_methods: ['Email'], step: 1 }],
1031
- message: 'Please sign',
1032
- expires_at: '2099-12-31T23:59:00Z',
1033
- copy_receivers: ['cc-signer-id']
1034
- )
1035
-
1036
- # Collect (positioned fields)
1037
- client.assignments.create(
1038
- 'document-id',
1039
- method: 'collect',
1040
- signers: [{ id: 'signer-1' }],
1041
- entries: [{ page_id: 'page-id', fields: [{ signer_id: 'signer-1', field_id: 'field-id',
1042
- display_settings: { left: 100, top: 100, width: 240,
1043
- height: 48, fontSize: 16 } }] }]
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
1044
218
  )
219
+ secret = endpoint.fetch('secret') # returned once; store it
1045
220
 
1046
- client.assignments.list # GET /assignments (scoped to the account)
1047
- client.assignments.estimate_cost('document-id', signers: [{ verification_method: 'Whatsapp' }])
1048
- client.assignments.reset_expiration('document-id', 'assignment-id', '2099-12-31T23:59:00Z')
1049
- client.assignments.reset_expiration('document-id', 'assignment-id', nil) # clears the expiry
1050
- client.assignments.resend_notification('document-id', 'assignment-id', 'signer-id')
1051
- client.assignments.estimate_resend_cost('document-id', 'assignment-id', 'signer-id')
1052
- client.assignments.whatsapp_notifications('document-id', 'assignment-id')
1053
-
1054
- # Signer perspective (signer-access-code authentication)
1055
- client.assignments.signer_document(signer_access_code: 'code', has_accepted_terms: true)
1056
- client.assignments.sign('document-id', 'assignment-id',
1057
- [{ item_id: 'i1', field_id: 'f1', page_id: 'p1', value: 'Alice' }],
1058
- signer_access_code: 'code')
1059
- client.assignments.decline('document-id', 'assignment-id', decline_reason: 'Clause 2', signer_access_code: 'code')
1060
- ```
1061
-
1062
- The `sign` body is the API's camelCase exception: the SDK maps `item_id`/`field_id`/`page_id` to
1063
- `itemId`/`fieldId`/`pageId` (camelCase input passes through). Assignment listing sends the camelCase `accountId`
1064
- query parameter.
1065
-
1066
- ### Signer documents (multi-document workflows)
1067
-
1068
- ```ruby
1069
- client.signer_documents.current('signer-id', signer_access_code: 'code')
1070
- client.signer_documents.list('signer-id', { status: 'pending_signature' }, signer_access_code: 'code')
1071
- client.signer_documents.search('signer-id', 'contract', signer_access_code: 'code')
1072
- client.signer_documents.list_as_workspace('signer-id') # same route with your API key
1073
- client.signer_documents.search_as_workspace('signer-id', 'contract')
1074
- client.signer_documents.sign_multiple(%w[document-id-1 document-id-2], signer_access_code: 'code')
1075
- client.signer_documents.decline_multiple(%w[document-id-1 document-id-2], decline_reason: 'No', signer_access_code: 'code')
1076
- client.signer_documents.download('signer-id', 'document-id', signer_access_code: 'code') # original PDF only
1077
- client.signer_documents.send_certified_copy(signer_access_code: 'code', document_id: 'document-id')
1078
- # => { 'available' => true, 'notification_method' => 'Email', 'resends_left' => 2, 'sent_to' => 'a***@example.com' }
1079
- client.signer_documents.download_certified_copy('download-token', pades: false) # binary PDF, token only
1080
- client.signer_documents.resend_certified_copy('download-token') # delivery metadata as above
1081
- ```
1082
-
1083
- Signer downloads require the access code and serve only `original`; use the workspace download API for other
1084
- artifacts. Certified copies are delivered by email or WhatsApp with their own download token. An expired token's
1085
- `302` is exposed as `ApiError`; the SDK does not follow it. For an envelope, pass `document_id` when selecting a
1086
- document or requesting its copy; `assignments.signer_document(expand: 'envelope', signer_access_code: 'code')`
1087
- includes the envelope's remaining documents.
221
+ verifier = Assinafy::Support::WebhookVerifier.new(secret)
222
+ return head(:unauthorized) unless verifier.verify_delivery(request.raw_post, request.headers)
1088
223
 
1089
- ### Templates
1090
-
1091
- ```ruby
1092
- client.templates.list(search: 'contract', per_page: 25)
1093
- client.templates.get('template-id')
1094
- client.templates.create({ file_path: './contract.pdf' }) # multipart upload, up to 25 MB
1095
- client.templates.create({ buffer: pdf_bytes, file_name: 'contract.pdf' })
1096
- client.templates.update('template-id', name: 'Renamed template')
1097
- client.templates.delete('template-id')
1098
- client.templates.download_page('template-id', 'page-id') # binary image bytes
224
+ event = verifier.extract_event(request.raw_post) # dedupe on the webhook-id header
1099
225
  ```
1100
226
 
1101
- `get`, `create`, `update`, `delete`, and `download_page` are supported by the deployed API beyond the OpenAPI
1102
- document. `create` requires a source file; the template name defaults to the file's name. Template generation
1103
- needs one entry per role, using a distinct existing signer ID or an `email`/`name` pair;
1104
- `role_id` comes from the template's `roles`. Cost estimation requires `role_id` but can omit the signer ID.
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`.
1105
230
 
1106
- ### Tags
231
+ ### Progress, artifacts, contracts and cleanup
1107
232
 
1108
233
  ```ruby
1109
- client.tags.list(search: 'contract')
1110
- client.tags.create(name: 'Contracts', color: 'ff8800')
1111
- client.tags.update('tag-id', name: 'Sales Contracts', color: nil) # nil clears the color
1112
- client.tags.delete('tag-id') # fails with 409 if the tag is in use
1113
- client.tags.delete('tag-id', force: true) # detaches from documents/templates first
1114
- ```
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']
1115
237
 
1116
- ### Fields
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') })
1117
240
 
1118
- ```ruby
1119
- client.fields.types # GET /field-types
1120
- client.fields.list(include_inactive: true, include_standard: false)
1121
- client.fields.create(type: 'text', name: 'Internal code', regex: '/[A-Z]{3}-[0-9]{4}/')
1122
- client.fields.get('field-id')
1123
- client.fields.update('field-id', name: 'Renamed')
1124
- client.fields.delete('field-id')
1125
-
1126
- client.fields.validate('field-id', 'ABC-1234') # workspace user
1127
- client.fields.validate('field-id', 'ABC-1234', signer_access_code: 'code') # signer
1128
- client.fields.validate_multiple(
1129
- [{ field_id: 'field-id-1', value: '1' }, { field_id: 'field-id-2', value: 'value@example.com' }],
1130
- signer_access_code: 'code'
1131
- )
241
+ client.documents.cancel(document.fetch('id')) # stop signing, keep the document
242
+ client.documents.delete(document.fetch('id'))
1132
243
  ```
1133
244
 
1134
- Single and batch field validation preserve explicit `nil` as JSON null. The API decides whether an empty value
1135
- is allowed by that field; a batch item must still contain its `value` key. Zero is a value.
1136
-
1137
- ### Webhooks
1138
-
1139
- ```ruby
1140
- client.webhooks.list_event_types # GET /webhooks/event-types
1141
- client.webhooks.list_endpoints # oldest first
1142
- client.webhooks.create_endpoint(url: 'https://example.com/webhooks/assinafy', email: 'ops@example.com',
1143
- events: %w[document_ready], signing_enabled: true)
1144
- client.webhooks.get_endpoint('webhook-endpoint-id')
1145
- client.webhooks.update_endpoint('webhook-endpoint-id', is_active: false)
1146
- client.webhooks.delete_endpoint('webhook-endpoint-id') # => nil
1147
- client.webhooks.endpoint_secret('webhook-endpoint-id') # => { 'secret' => 'whsec_...' }
1148
- client.webhooks.rotate_endpoint_secret('webhook-endpoint-id')
1149
- client.webhooks.rotate_endpoint_secret('webhook-endpoint-id', keep_previous: true) # 24-hour overlap
1150
- client.webhooks.test_endpoint('webhook-endpoint-id') # one manual delivery; returns its dispatch entry
1151
-
1152
- client.webhooks.list_dispatches(endpoint_id: 'webhook-endpoint-id', delivered: false, per_page: 50)
1153
- client.webhooks.retry_dispatch('dispatch-id')
1154
-
1155
- # Subscription operations act on the account's oldest endpoint:
1156
- client.webhooks.get # nil on 404
1157
- client.webhooks.register(url: 'https://example.com/webhooks/assinafy', email: 'ops@example.com',
1158
- events: %w[document_ready signer_signed_document])
1159
- client.webhooks.inactivate # stop deliveries, keep the event set
1160
- ```
1161
-
1162
- `register` accepts only `url`, `email`, `events`, and `is_active`; other keys raise `ValidationError`. Use the
1163
- endpoint operations for names, signing, and several endpoints.
1164
-
1165
- ## Responses
1166
-
1167
- Most JSON successes use a `{ "status": ..., "message": ..., "data": ... }` envelope. The SDK
1168
- returns the `data` payload (a Hash for single resources, an Array for collection bodies). For
1169
- documented no-data envelopes containing only `status`/`message`, it returns `nil`; deployed API
1170
- versions that add `data` are passed through. Binary endpoints (`download`, `thumbnail`,
1171
- `download_page`, `download_signature`) return raw bytes as an ASCII-8BIT `String`, and
1172
- delete-style endpoints return `nil`.
1173
-
1174
- OAuth endpoints are the exception: `/oauth/token`, `/oauth/revoke`, `/oauth/userinfo`, and the `.well-known`
1175
- metadata documents answer with flat RFC 6749 / OIDC / RFC 8615 objects rather than the envelope, and the SDK
1176
- returns those bodies unchanged.
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.
1177
248
 
1178
- The [SDK API reference](docs/API_REFERENCE.md) maps every API operation to its Ruby method and documents exact
1179
- authentication, parameters, request bodies, success responses, and every published schema property.
249
+ ## Responses and errors
1180
250
 
1181
- ## Pagination
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.
1182
254
 
1183
- Most `*.list*` methods return `{ data: [...], meta: { ... } }` when the API includes pagination
1184
- headers. Ruby-style `per_page:` is transparently converted to the documented `per-page` query
1185
- parameter (values above the API's maximum are clamped server-side). Endpoints that send no pagination headers
1186
- (e.g. `accounts.list`) return `{ data: [...] }` without `meta`.
1187
-
1188
- ```ruby
1189
- result = client.documents.list(page: 2, per_page: 25)
1190
- result[:data] # => Array<Hash>
1191
- result[:meta] # => { current_page: 2, per_page: 25, total: 138, last_page: 6 }
1192
- ```
1193
-
1194
- ## Errors
1195
-
1196
- The SDK raises one of:
1197
-
1198
- - `Assinafy::ValidationError` — caller-side input invalid (missing IDs, bad email, etc.), raised before any request.
1199
- - `Assinafy::ApiError` — the API returned a non-2xx status. Includes `status_code`, `message`, `error_name`,
1200
- `error_code`, and `response_data`; on a `403`, `context[:www_authenticate]` names the scope an OAuth token is
1201
- missing.
1202
- - `Assinafy::OAuthError` — an OAuth endpoint failed. Subclasses `ApiError`, and adds `error` and
1203
- `error_description` from the flat RFC 6749 body.
1204
- - `Assinafy::NetworkError` — Faraday connection error, timeout, or TLS failure.
1205
- - `Assinafy::Error` — base class; other unexpected errors get wrapped here with the operation label.
1206
-
1207
- All inherit a `#context` Hash with debugging metadata.
1208
-
1209
- Use `ApiError#error_code` for actionable refusals such as `PlanRestricted`, `InsufficientScope`,
1210
- `ContractChanged`, or `CreditCeilingExceeded`. Field validation details remain in `response_data['errors']`,
1211
- an array of `{ 'field' => ..., 'code' => ..., 'message' => ... }`; localized messages are for display, not branching.
1212
-
1213
- ## 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 |
1214
261
 
1215
- ```bash
1216
- bundle exec rake spec # RSpec, including a coverage matrix
1217
- bundle exec rubocop --cache false # Linting
1218
- bundle exec bundler-audit check --update # Dependency CVEs
1219
- rbs -I sig validate # Published signatures (install rbs outside the bundle)
1220
- ruby scripts/check_api_contract.rb --file path/to/openapi.json # validate a local contract document
1221
- ```
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.
1222
265
 
1223
- The coverage spec validates the committed route-to-method inventory, public wrappers, aliases, and resource
1224
- mappings without network access. Ordinary pull-request CI remains network-independent; a weekly scheduled job runs
1225
- `scripts/check_api_contract.rb` against the upstream document.
266
+ ## Resources
1226
267
 
1227
- ### 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.
1228
271
 
1229
- The suite in [`spec/integration/`](spec/integration/live_sandbox_spec.rb) exercises safe sandbox workflows across
1230
- every workspace resource. Signer-code, OTP, password, social-login, API-key mutation, signature upload, and
1231
- irreversible sign/decline calls are wire-contract tested in the default suite but are not live-automated without
1232
- their one-time credentials or explicit state changes. The live suite is excluded from the default run and only
1233
- executes when `ASSINAFY_LIVE=1` is set with credentials:
272
+ ## Development
1234
273
 
1235
274
  ```bash
1236
- ASSINAFY_LIVE=1 \
1237
- ASSINAFY_API_KEY=... \
1238
- ASSINAFY_ACCOUNT_ID=... \
1239
- ASSINAFY_TEST_EMAIL=recipient1@example.com \
1240
- ASSINAFY_TEST_EMAIL2=recipient2@example.com \
1241
- ASSINAFY_TEMPLATE_ID=configured-template-id \
1242
- ASSINAFY_BASE_URL=https://sandbox.assinafy.com.br/v1 \
1243
- 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
1244
280
  ```
1245
281
 
1246
- `ASSINAFY_TEMPLATE_ID` must identify a sandbox template with a `Signer` role configured in the
1247
- application. Without it, the positive template-generation example is skipped. Supply different test
1248
- recipients for its roles. OAuth browser consent is tested separately with a registered app, an HTTPS
1249
- callback, and the matching authorization server; sandbox keys are not production OAuth credentials.
1250
-
1251
- > 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`.
1252
-
1253
- ## Contributing
1254
-
1255
- Pull requests and issues are welcome at <https://github.com/assinafy/ruby-sdk>.
1256
-
1257
- ## 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.
1258
284
 
1259
- MIT. See [LICENSE](LICENSE).
285
+ Pull requests and issues are welcome at <https://github.com/assinafy/ruby-sdk>. License: [MIT](LICENSE).