### get() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/webhook-resource.md Example of retrieving the current webhook subscription and checking for null to handle the case where nothing is configured. ```php $sub = $client->webhooks()->get(); if ($sub === null) { /* nothing configured */ } ``` -------------------------------- ### Create template usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/template-resource.md Shows how to create a template from a PDF file and wait until it is ready. The template starts in 'Uploaded' state and pages render asynchronously. ```php $template = $client->templates()->create('/path/agreement.pdf'); $ready = $client->templates()->waitUntilReady($template['id']); ``` -------------------------------- ### Install SDK version 2.7.1 Source: https://github.com/assinafy/php-sdk/blob/main/docs/INSTALLATION.md Installs the exact version described by this documentation. Use this to match the documented behavior. ```bash composer require assinafy/php-sdk:2.7.1 ``` -------------------------------- ### download() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/signer-document-resource.md Example call to download() that saves the certificated artifact to a local file. ```php file_put_contents('my-copy.pdf', $client->signerDocuments()->download( $signerId, $documentId, $accessCode, DocumentResource::ARTIFACT_CERTIFICATED, )); ``` -------------------------------- ### Using protectedResourceMetadata() and authorizationServerMetadata() to start authorization Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/oauth-resource.md Example that fetches protected-resource metadata, then authorization server metadata, and passes the issuer and authorization_endpoint into startAuthorization(). This is the recommended flow for obtaining the correct endpoints. ```php $meta = $oauth->protectedResourceMetadata(); $authMeta = $oauth->authorizationServerMetadata($meta['authorization_servers'][0]); $start = $oauth->startAuthorization($redirectUri, $scopes, [ 'issuer' => $authMeta['issuer'], 'authorization_endpoint' => $authMeta['authorization_endpoint'], ]); ``` -------------------------------- ### Docker Compose commands for Assinafy SDK Source: https://github.com/assinafy/php-sdk/blob/main/docs/INSTALLATION.md Starts the PHP 8.5 FPM and Nginx environment, installs dependencies, runs unit tests, and stops the containers. The UID/GID mapping defaults to 1000:1000 and the web service listens on http://localhost:8080. ```bash export ASSINAFY_DOCKER_UID="$(id -u)" export ASSINAFY_DOCKER_GID="$(id -g)" docker compose up -d --build docker compose exec php composer install docker compose exec php vendor/bin/phpunit --testsuite=unit docker compose down ``` -------------------------------- ### Get template usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/template-resource.md Shows how to retrieve a template and extract role IDs from the response. ```php $template = $client->templates()->get($templateId); $roleIds = array_column($template['roles'], 'id'); ``` -------------------------------- ### Run Quickstart Script Source: https://github.com/assinafy/php-sdk/blob/main/docs/INSTALLATION.md Sets ASSINAFY_API_KEY and ASSINAFY_ACCOUNT_ID, then runs the quickstart script for read-only connectivity checks. Optional environment variables ASSINAFY_TEST_SEARCH_TERM, ASSINAFY_TEST_TEMPLATE_ID, ASSINAFY_TEST_SIGNER_ID, and ASSINAFY_TEST_SIGNER_ACCESS_CODE enable additional checks. ```bash php docs/quickstart.php ``` -------------------------------- ### startAuthorization() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/oauth-resource.md Starts the OAuth flow by generating a code_verifier and state, and returns a transaction array to persist in the user's session. The example passes the redirect URI and scopes, stores the transaction in $_SESSION, and redirects the browser to the authorization URL. ```php $start = $oauth->startAuthorization('https://app.example.com/callback', [ OAuthResource::SCOPE_DOCUMENTS_READ, OAuthResource::SCOPE_DOCUMENTS_WRITE, OAuthResource::SCOPE_OFFLINE_ACCESS, ]); $_SESSION['assinafy_oauth'] = $start; header('Location: ' . $start['authorization_url']); ``` -------------------------------- ### socialLoginUrl usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/auth-resource.md Shows how to redirect the user to the legacy browser OAuth start URL. ```php header('Location: ' . $public->auth()->socialLoginUrl()); ``` -------------------------------- ### AccountResource::get() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/account-resource.md Calls get() to retrieve the configured account. ```php $account = $client->accounts()->get(); ``` -------------------------------- ### get() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/user-resource.md Fetches the current user's profile and prints the email address. ```php $me = $client->users()->get(); echo $me['email']; ``` -------------------------------- ### activate() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/webhook-resource.md Example call to activate the webhook subscription. ```php $client->webhooks()->activate(); ``` -------------------------------- ### Initialize OAuth client and start authorization Source: https://github.com/assinafy/php-sdk/blob/main/README.en.md Sets up the OAuth client with sandbox credentials and starts the authorization flow, generating a code_verifier and state. Sends the user to the authorization URL and stores the transaction in the session. ```php use Assinafy\SDK\Resources\OAuthResource; $oauthBaseUrl = Configuration::SANDBOX_BASE_URL; $expectedIssuer = 'https://auth-sandbox.assinafy.com.br'; $oauthClient = AssinafyClient::forAuth($oauthBaseUrl); $oauth = $oauthClient->oauth( (string) getenv('ASSINAFY_OAUTH_CLIENT_ID'), (string) getenv('ASSINAFY_OAUTH_CLIENT_SECRET') ?: null, ); $server = $oauth->authorizationServerMetadata($expectedIssuer); if (($server['issuer'] ?? null) !== $expectedIssuer) { throw new RuntimeException('Unexpected OAuth issuer'); } // 1. Send the browser to Assinafy, keeping the transaction in the user's session. $start = $oauth->startAuthorization('https://app.example.com/callback', [ OAuthResource::SCOPE_DOCUMENTS_READ, OAuthResource::SCOPE_DOCUMENTS_WRITE, OAuthResource::SCOPE_OPENID, OAuthResource::SCOPE_PROFILE, OAuthResource::SCOPE_EMAIL, OAuthResource::SCOPE_OFFLINE_ACCESS, ], ['issuer' => $server['issuer'], 'authorization_endpoint' => $server['authorization_endpoint']]); $_SESSION['assinafy_oauth'] = $start + ['created_at' => time()]; header('Location: ' . $start['authorization_url'], true, 302); exit; ``` -------------------------------- ### create() Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/template-resource.md Creates a template by uploading a PDF file. The template starts in 'Uploaded' state and pages render asynchronously; poll get() until status is 'Ready'. ```APIDOC ## POST /accounts/{account_id}/templates ### Description Creates a template by uploading a PDF file. The template starts in 'Uploaded' state and pages render asynchronously; poll get() until status is 'Ready'. ### Method POST ### Endpoint /accounts/{account_id}/templates ### Parameters #### Path Parameters - **account_id** (string) - Required - The account identifier. #### Request Body - **file** (file) - Required - The PDF file to upload. Must be a PDF and not exceed 25 MB. ### Request Example ``` POST /accounts/{account_id}/templates Content-Type: multipart/form-data file=@/path/to/agreement.pdf ``` ### Response #### Success Response (200) - **id** (string) - The template ID. - **status** (string) - The initial status, 'Uploaded'. - **roles** (array) - Roles associated with the template. - **default_document_tags** (array) - Default document tags. #### Response Example ```json { "id": "template_123", "status": "Uploaded", "roles": [], "default_document_tags": [] } ``` ### Errors - **ValidationException** - When the file is missing, not a PDF, or larger than 25 MB. ### Example Usage ```php $template = $client->templates()->create('/path/agreement.pdf'); $ready = $client->templates()->waitUntilReady($template['id']); ``` ``` -------------------------------- ### list() and listAsWorkspace() usage examples Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/signer-document-resource.md Example calls to list a signer's documents using either the signer access code or workspace credentials. ```php $inbox = $client->signerDocuments()->list($signerId, $accessCode); $inbox = $client->signerDocuments()->listAsWorkspace($signerId, ['per-page' => 20]); ``` -------------------------------- ### Wait until ready usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/template-resource.md Shows how to wait for a template to become ready with a custom timeout. ```php $ready = $client->templates()->waitUntilReady($templateId, maxWaitSeconds: 120); ``` -------------------------------- ### identityVerification() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/signer-session-resource.md Shows how to call identityVerification() and check the can_start flag to conditionally show a 'start verification' button. The returned url is a bearer credential (contains #t=) and should be kept out of logs/browser storage; null outside Pending. ```php $state = $client->signerSession()->identityVerification($accessCode); if ($state['can_start']) { /* show "start verification" button */ } ``` -------------------------------- ### Clone and install development dependencies Source: https://github.com/assinafy/php-sdk/blob/main/docs/INSTALLATION.md Clones the public mirror of the SDK repository and installs development dependencies for SDK development. ```bash git clone https://github.com/assinafy/php-sdk.git cd php-sdk composer install ``` -------------------------------- ### Iso8601 usage examples Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/support-internals.md Shows example calls to Iso8601::reasonInvalid() with valid and invalid date-time strings, demonstrating the expected return values. ```php Iso8601::reasonInvalid('2026-12-31T23:59:59Z'); // null (valid) Iso8601::reasonInvalid('2026-12-31 23:59:59'); // REASON_FORMAT (no T / no offset) ``` -------------------------------- ### Install Assinafy PHP SDK via Composer Source: https://github.com/assinafy/php-sdk/blob/main/README.en.md Install the SDK using Composer. The package is published on Packagist as assinafy/php-sdk, so no repository configuration is needed. ```bash composer require assinafy/php-sdk ``` -------------------------------- ### search() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/signer-document-resource.md Example call to search a signer's documents for a term like 'agreement'. ```php $matches = $client->signerDocuments()->search($signerId, $accessCode, 'agreement'); ``` -------------------------------- ### register() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/webhook-resource.md Example call to register a webhook subscription with a URL and email. The events array is empty, so DEFAULT_EVENTS will be sent. ```php $client->webhooks()->register('https://example.com/hooks/assinafy', 'ops@example.com'); ``` -------------------------------- ### getAccountId usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/webhook-event-parser.md Shows how to call getAccountId with a decoded event envelope to obtain the workspace ID, with a comment showing an example value. ```php $accountId = $parser->getAccountId($event); // 'account-id' ``` -------------------------------- ### Usage example: startIdentityVerification() with redirect Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/signer-session-resource.md Example usage of startIdentityVerification(). Redirects the signer to the exact returned URL including the fragment. The expires_at field can be null. Declined/Abandoned statuses require a new document and assignment. ```php $session = $client->signerSession()->startIdentityVerification($accessCode, true); header('Location: ' . $session['url']); ``` -------------------------------- ### Instantiate GuzzleHttpClient and make a GET request Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/http-layer.md Creates a `GuzzleHttpClient` with a `Configuration` and performs a GET request to `documents/statuses`. The response data is an array of status objects. ```php use Assinafy\SDK\Http\GuzzleHttpClient; $transport = new GuzzleHttpClient($config); $response = $transport->get('documents/statuses'); $data = $response->getData(); // ['0' => ['code' => 'uploading', 'deletable' => false], …] ``` -------------------------------- ### get() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/field-resource.md Retrieves a field definition by its ID. ```php $field = $client->fields()->get($fieldId); ``` -------------------------------- ### Constructor usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/assinafy-client.md Creates a client with a Configuration using environment variables and the sandbox base URL. ```php use Assinafy\SDK\AssinafyClient; use Assinafy\SDK\Configuration; $client = new AssinafyClient(new Configuration( apiKey: (string) getenv('ASSINAFY_API_KEY'), accountId: (string) getenv('ASSINAFY_ACCOUNT_ID'), baseUrl: Configuration::SANDBOX_BASE_URL, )); ``` -------------------------------- ### Login usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/auth-resource.md Shows how to obtain a public client, log in with email and password, and create a bearer client using the returned access token and first account ID. ```php $public = AssinafyClient::forAuth(); $session = $public->auth()->login('user@example.com', getenv('ASSINAFY_PASSWORD')); $client = AssinafyClient::forBearer($session['access_token'], $session['accounts'][0]['id']); ``` -------------------------------- ### create() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/assinafy-client.md Creates a client using the create() factory with environment variables and sandbox base URL. ```php $client = AssinafyClient::create( apiKey: (string) getenv('ASSINAFY_API_KEY'), accountId: (string) getenv('ASSINAFY_ACCOUNT_ID'), baseUrl: Configuration::SANDBOX_BASE_URL, ); ``` -------------------------------- ### Set up Assinafy client for sandbox Source: https://github.com/assinafy/php-sdk/blob/main/docs/EXAMPLES.md Initializes the AssinafyClient with API key, account ID, and sandbox base URL, reading required credentials from environment variables. Throws a RuntimeException if any required environment variable is missing. Do not log or print the API key or other sensitive data. ```php signerSession()->identityVerification($signerAccessCode); if ($session['can_start']) { $session = $client->signerSession()->startIdentityVerification($signerAccessCode, true); } $captureUrl = $session['url'] ?? null; ``` -------------------------------- ### getSigningProgress usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/document-resource.md Calls getSigningProgress and passes the signed and total values to a renderProgressBar function. One API call (get()). ```php $p = $client->documents()->getSigningProgress($documentId); renderProgressBar($p['signed'], $p['total']); ``` -------------------------------- ### Instantiate Configuration with environment variables Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/configuration.md Creates a Configuration object using environment variables for the API key and account ID, and sets the sandbox base URL. ```php $config = new Configuration( apiKey: (string) getenv('ASSINAFY_API_KEY'), accountId: (string) getenv('ASSINAFY_ACCOUNT_ID'), baseUrl: Configuration::SANDBOX_BASE_URL, timeout: 30, connectTimeout: 10, ); ``` -------------------------------- ### startAuthorization() Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/oauth-resource.md Begins a connection by minting PKCE material and building the authorization URL. This method makes no HTTP request and returns a transaction array to persist in the user's session. ```APIDOC ## startAuthorization() ### Description Begins a connection by minting PKCE material and building the authorization URL. Pure string construction — makes **no** HTTP request. ### Method startAuthorization ### Signature ```php public function startAuthorization( string $redirectUri, array $scopes, #\[SensitiveParameter\] array $options = [] ): array ``` ### Parameters - **redirectUri** (string) - Required - One of the application's registered URIs, character for character — `…/callback` and `…/callback/` are different. - **scopes** (array) - Required - The permissions to request, e.g. `self::SCOPE_DOCUMENTS_WRITE`. The user approves all of them or none. - **options** (array) - Optional - Overrides: `state`, `code_verifier`, `nonce`, `issuer`, `authorization_endpoint`, `resource`. Every one has a correct default; supply `issuer`/`authorization_endpoint` from `authorizationServerMetadata()` to avoid hardcoding them. ### Returns - **array** - The transaction to persist: `{ authorization_url, state, code_verifier, code_challenge, nonce? (only with openid scope), redirect_uri, issuer, resource }`. ### Throws - **ValidationException** - On a non-HTTPS or fragment-bearing redirect URI, an empty scope list, an invalid RFC 6749 scope token, or an out-of-grammar verifier. ### Example ```php $start = $oauth->startAuthorization('https://app.example.com/callback', [ OAuthResource::SCOPE_DOCUMENTS_READ, OAuthResource::SCOPE_DOCUMENTS_WRITE, OAuthResource::SCOPE_OFFLINE_ACCESS, ]); $_SESSION['assinafy_oauth'] = $start; header('Location: ' . $start['authorization_url']); ``` ``` -------------------------------- ### create() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/field-resource.md Creates a text field with a regex pattern and required flag. ```php $field = $client->fields()->create('text', 'Job title', ['regex' => '^[A-Z].*$', 'is_required' => true]); ``` -------------------------------- ### Create AssinafyClient with sandbox credentials and access resources Source: https://github.com/assinafy/php-sdk/blob/main/ARCHITECTURE.md Initializes the AssinafyClient using environment variables for API key and account ID, validates them, and creates the client with the sandbox base URL. Then accesses the documents resource and fetches the current user. ```php use Assinafy\SDK\AssinafyClient; use Assinafy\SDK\Configuration; $apiKey = getenv('ASSINAFY_API_KEY'); $accountId = getenv('ASSINAFY_ACCOUNT_ID'); if (!is_string($apiKey) || $apiKey === '' || !is_string($accountId) || $accountId === '') { throw new RuntimeException('Assinafy sandbox credentials are not configured.'); } $client = AssinafyClient::create( apiKey: $apiKey, accountId: $accountId, baseUrl: Configuration::SANDBOX_BASE_URL, ); $documents = $client->documents(); $user = $client->users()->get(); ``` -------------------------------- ### stats() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/user-resource.md Fetches monthly statistics for the user across all accounts. ```php $series = $client->users()->stats('monthly'); ``` -------------------------------- ### Configure AssinafyClient for Production Source: https://github.com/assinafy/php-sdk/blob/main/README.en.md Create a client for production using the default base URL. Requires ASSINAFY_API_KEY and ASSINAFY_ACCOUNT_ID environment variables. ```php oauth( (string) getenv('ASSINAFY_OAUTH_CLIENT_ID'), (string) getenv('ASSINAFY_OAUTH_CLIENT_SECRET') ?: null, ); ``` -------------------------------- ### deactivate() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/webhook-resource.md Example call to deactivate the webhook subscription. ```php $client->webhooks()->deactivate(); ``` -------------------------------- ### listTags() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/document-resource.md Shows how to call listTags on the documents client to retrieve the tags for a document. ```php $tags = $client->documents()->listTags($documentId); ``` -------------------------------- ### get() method signature Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/webhook-resource.md Gets the current webhook subscription using the oldest endpoint GET /accounts/{account_id}/webhooks/subscriptions. Returns null when never configured, or an inactive subscription with an empty url for a new account. ```php /** * Get the current webhook subscription — the oldest endpoint (or null if none exists). * `GET /accounts/{account_id}/webhooks/subscriptions` * * @return array|null the subscription, or null when none exists; a new * account can instead return an inactive subscription with an empty `url` */ public function get(): ?array ``` -------------------------------- ### declineMultiple() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/signer-document-resource.md Example call to declineMultiple() with an access code, document IDs, and a reason. ```php $client->signerDocuments()->declineMultiple($accessCode, ['doc-1'], 'The payment terms are wrong'); ``` -------------------------------- ### mfaMethods() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/user-resource.md Fetches MFA methods and prints the number of remaining recovery codes. ```php $mfa = $client->users()->mfaMethods(); echo $mfa['recovery_codes_remaining']; ``` -------------------------------- ### socialLogin usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/auth-resource.md Shows how to sign in with Google using an ID token obtained in the browser, passing hasAcceptedTerms as true for first-time sign-in. ```php $session = $public->auth()->socialLogin(AuthResource::PROVIDER_GOOGLE, $googleIdToken, true); ``` -------------------------------- ### signMultiple() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/signer-document-resource.md Example call to signMultiple() with an access code and an array of document IDs. ```php $client->signerDocuments()->signMultiple($accessCode, ['doc-1', 'doc-2']); ``` -------------------------------- ### createFromTemplate() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/document-resource.md Shows how to create a document from a template by fetching roles and passing signer details. The call also dispatches assignment and includes options like message and expiration. ```php $roles = $client->templates()->get($templateId)['roles']; $document = $client->documents()->createFromTemplate( $templateId, [['role_id' => $roles[1]['id'], 'id' => $signerId, 'verification_method' => 'Email']], ['message' => 'Please sign', 'expires_at' => '2026-12-31T23:59:59Z'], ); ``` -------------------------------- ### current() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/signer-document-resource.md Example call to retrieve the current document for a signer using their access code. ```php $doc = $client->signerDocuments()->current($signerId, $accessCode); ``` -------------------------------- ### fromArray() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/configuration.md Creates a Configuration instance from an array with `api_key` and `account_id` keys, using environment variables for the API key. ```php $config = Configuration::fromArray(['api_key' => getenv('ASSINAFY_API_KEY'), 'account_id' => 'acct_1']); ``` -------------------------------- ### startTotpEnrollment() Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/user-resource.md Starts enrolling an authenticator app by creating an unconfirmed method and returning its shared secret. The provisioning URI should be rendered as a QR code; 2FA is not active until confirmation. ```APIDOC ## startTotpEnrollment() ### Description Starts enrolling an authenticator app. Creates an unconfirmed method and returns its shared secret (returned only by this call). Render `provisioning_uri` as a QR code; 2FA is not active until `confirmTotpEnrollment()` succeeds. ### Method POST ### Endpoint `/users/self/mfa/totp` ### Parameters #### Optional Parameters - **label** (?string) - Optional - A label for the authenticator enrollment. - **accessToken** (?string) - Optional - Access token for authentication; required for public clients. ### Request Example ```php $enrollment = $client->users()->startTotpEnrollment('My phone'); // show QR for $enrollment['provisioning_uri'], keep $enrollment['id'] ``` ### Response #### Success Response - **id** (string) - The ID of the unconfirmed method. - **secret** (string) - The shared secret for the enrollment. - **provisioning_uri** (string) - URI to render as a QR code. #### Response Example ```json { "id": "string", "secret": "string", "provisioning_uri": "string" } ``` ### Errors - **ValidationException** - Thrown when called on a public client without an access token. ``` -------------------------------- ### get() Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/field-resource.md Retrieves a single field definition. Sends a GET request to /accounts/{account_id}/fields/{field_id}. ```APIDOC ## GET /accounts/{account_id}/fields/{field_id} ### Description Retrieves a single field definition. ### Method GET ### Endpoint /accounts/{account_id}/fields/{field_id} ### Parameters #### Path Parameters - **account_id** (string) - Required - The account identifier. - **field_id** (string) - Required - The field identifier. ### Request Example ``` GET /accounts/{account_id}/fields/{field_id} ``` ### Response #### Success Response (200) - Returns the field definition as an array. #### Response Example ```json { "id": "field_id", "type": "text", "name": "Job title" } ``` ### Error Handling - **ValidationException** - When fieldId is empty. - **ApiException** - 404 when the field does not exist. ``` -------------------------------- ### Install Monolog for PSR-3 logging Source: https://github.com/assinafy/php-sdk/blob/main/docs/INSTALLATION.md Optionally installs Monolog to enable PSR-3 logging integrations with the SDK. ```bash composer require monolog/monolog ``` -------------------------------- ### startTotpEnrollment() method signature Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/user-resource.md Starts enrollment of an authenticator app via POST /users/self/mfa/totp. Returns an array with optional id, secret, and provisioning_uri. Throws ValidationException when called on a public client without an access token. ```php /** * Start enrolling an authenticator app. * `POST /users/self/mfa/totp` * * @return array{id?: string, secret?: string, provisioning_uri?: string} * @throws ValidationException when called on a public client without an access token */ public function startTotpEnrollment( ?string $label = null, #\[\SensitiveParameter\] ?string $accessToken = null ): array ``` -------------------------------- ### startTotpEnrollment() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/user-resource.md Creates an unconfirmed method and returns its shared secret (returned only by this call). Render provisioning_uri as a QR code; 2FA is not active until confirmTotpEnrollment() succeeds. ```php $enrollment = $client->users()->startTotpEnrollment('My phone'); // show QR for $enrollment['provisioning_uri'], keep $enrollment['id'] ``` -------------------------------- ### normalizePhoneNumber() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/signer-resource.md Example call to normalizePhoneNumber() with a Brazilian phone number containing separators, returning the E.164 format. ```php SignerResource::normalizePhoneNumber('+55 (48) 99999-0000'); // '+5548999990000' ``` -------------------------------- ### Run live integration tests with sandbox credentials Source: https://github.com/assinafy/php-sdk/blob/main/README.en.md Opt-in live integration tests that reject the production API URL unless overridden. Secrets are entered without shell history. Covers document preparation and assignment management with reserved example.com recipients. ```bash read -rs ASSINAFY_API_KEY export ASSINAFY_API_KEY export ASSINAFY_ACCOUNT_ID='sandbox-account-id' export ASSINAFY_BASE_URL='https://sandbox.assinafy.com.br/v1' export ASSINAFY_INTEGRATION=1 vendor/bin/phpunit --testsuite=integration ``` -------------------------------- ### download() usage examples Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/document-resource.md Saves the certificated artifact as signed.pdf and the PAdES artifact as pades.pdf using the default and explicit artifact constants. ```php file_put_contents('signed.pdf', $client->documents()->download($documentId)); file_put_contents('pades.pdf', $client->documents()->download($documentId, DocumentResource::ARTIFACT_PADES)); ``` -------------------------------- ### GET /accounts/{account_id}/signers/{signer_id} Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/endpoints.md Retrieves a specific signer by ID. The SDK method is signers()->get($id). ```APIDOC ## GET /accounts/{account_id}/signers/{signer_id} ### Description Retrieves the details of a specific signer. ### Method GET ### Endpoint /accounts/{account_id}/signers/{signer_id} ### Parameters #### Path Parameters - **account_id** (string) - Required - The account identifier. - **signer_id** (string) - Required - The signer identifier. ### Response #### Success Response (200) - **id** (string) - The signer identifier. - **full_name** (string) - The signer's full name. - **email** (string) - The signer's email. - **whatsapp_phone_number** (string) - The signer's WhatsApp phone number. - **government_id** (string) - The signer's government ID (CPF/CNPJ). #### Response Example ```json { "id": "signer_id", "full_name": "John Doe", "email": "john@example.com", "whatsapp_phone_number": "+5511999999999", "government_id": "12345678900" } ``` ``` -------------------------------- ### GET /accounts/{account_id} Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/endpoints.md Retrieves a specific account by its ID. Requires Key authentication. The SDK method is accounts()->get(). ```APIDOC ## GET /accounts/{account_id} ### Description Retrieves a specific account by its ID. ### Method GET ### Endpoint /accounts/{account_id} ### Authentication Key ### SDK Method accounts()->get() ``` -------------------------------- ### Using the static PKCE helpers Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/oauth-resource.md Example usage of the three static helpers: createCodeVerifier, codeChallenge, and createState. The verifier is passed to codeChallenge to derive the challenge, and the state is generated for the authorization attempt. ```php $verifier = OAuthResource::createCodeVerifier(); $challenge = OAuthResource::codeChallenge($verifier); $state = OAuthResource::createState(); ``` -------------------------------- ### Configure AssinafyClient for Sandbox Source: https://github.com/assinafy/php-sdk/blob/main/README.en.md Create a client for development using the sandbox base URL. Only the base URL changes from the production configuration. ```php $sandbox = AssinafyClient::create( apiKey: (string) getenv('ASSINAFY_API_KEY'), accountId: (string) getenv('ASSINAFY_ACCOUNT_ID'), baseUrl: Configuration::SANDBOX_BASE_URL, ); ``` -------------------------------- ### validateMultiple() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/field-resource.md Example of calling validateMultiple() with two values for the same field. Iterates over the verdicts and prints the field_id and error_message for any that failed. ```php $verdicts = $client->fields()->validateMultiple([ ['field_id' => $cpfFieldId, 'value' => '111.444.777-35'], ['field_id' => $cpfFieldId, 'value' => '123'], ]); foreach ($verdicts as $v) { if (!$v['success']) { echo $v['field_id'] . ': ' . $v['error_message']; } } ``` -------------------------------- ### Start identity verification capture Source: https://github.com/assinafy/php-sdk/blob/main/README.en.md Opens the identity verification capture flow after explicit signer consent, using the signer access code. Checks if capture can start, then starts it with liveness enabled. The resulting URL is a bearer credential and must be kept out of logs and browser storage. ```php $state = $client->signerSession()->identityVerification($signerAccessCode); if ($state['can_start']) { $state = $client->signerSession()->startIdentityVerification($signerAccessCode, true); } $captureUrl = $state['url'] ?? null; ``` -------------------------------- ### forAuth() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/assinafy-client.md Creates an unauthenticated client, logs in, handles MFA, and then creates a bearer client. ```php $client = AssinafyClient::forAuth(); $session = $client->auth()->login('user@example.com', (string) getenv('ASSINAFY_PASSWORD')); if (isset($session['mfa_token'])) { $session = $client->auth()->verifyMfa($session['mfa_token'], $authCode); } $bearer = AssinafyClient::forBearer($session['access_token'], $session['accounts'][0]['id']); ``` -------------------------------- ### Initialize OAuth client for sandbox Source: https://github.com/assinafy/php-sdk/blob/main/docs/EXAMPLES.md Sets up the OAuth client using the sandbox base URL and expected issuer. The client secret is optional for public applications. ```php use Assinafy\SDK\Exceptions\ApiException; use Assinafy\SDK\Resources\OAuthResource; $oauthBaseUrl = Configuration::SANDBOX_BASE_URL; $expectedIssuer = 'https://auth-sandbox.assinafy.com.br'; $oauthClient = AssinafyClient::forAuth($oauthBaseUrl); $oauth = $oauthClient->oauth( requiredEnv('ASSINAFY_OAUTH_CLIENT_ID'), getenv('ASSINAFY_OAUTH_CLIENT_SECRET') ?: null, // null for a public application ); ``` -------------------------------- ### types() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/field-resource.md Example of calling types() and de-duplicating the result on 'type' using array_unique and array_column, as the live list repeats 'email'. ```php $types = array_unique(array_column($client->fields()->types(), 'type')); ``` -------------------------------- ### Constructor Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/oauth-resource.md Initializes the Assinafy PHP SDK client with the required HTTP client and configuration, and optional logger, client ID, client secret, and discovery transport. ```APIDOC ## Constructor ### Description Initializes the Assinafy PHP SDK client. Requires an HTTP client and configuration. Optional parameters include a logger, client ID, client secret, and a discovery transport closure. ### Method __construct ### Signature ```php public function __construct( HttpClientInterface $httpClient, #\[SensitiveParameter\] Configuration $config, ?LoggerInterface $logger = null, string $clientId = '', #\[SensitiveParameter\] ?string $clientSecret = null, ?\Closure $discoveryTransport = null ) ``` ### Parameters - **$httpClient** (HttpClientInterface) - Required - Main transport (uses `$config` base URL). - **$config** (Configuration) - Required - Supplies the API origin for the `resource` parameter. - **$logger** (LoggerInterface|null) - Optional - Default: `null` - Forwarded to the discovery transport. - **$clientId** (string) - Optional - Default: `''` - Non-empty required (`ValidationException`). - **$clientSecret** (string|null) - Optional - Default: `null` - Confidential apps only; blank-when-supplied → `ValidationException`. - **$discoveryTransport** (\Closure(string): HttpClientInterface|null) - Optional - Default: Guzzle per origin (`Configuration::forPublic($origin)`) - Builds the credential-free client for discovery origins. ### Throws - **ValidationException** - On an empty client ID or a present-but-blank secret. ### Notes `__debugInfo()` returns `{ client_id, client_type: 'public'|'confidential' }` (the secret never appears). ``` -------------------------------- ### getEventData usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/webhook-event-parser.md Shows how to call getEventData with a decoded event envelope. The result is an array representing the entity, with a comment showing an example structure. ```php $signer = $parser->getEventData($event); // ['id' => …, 'type' => 'Signer', 'full_name' => …] ``` -------------------------------- ### Verify Assinafy SDK installation Source: https://github.com/assinafy/php-sdk/blob/main/docs/INSTALLATION.md Constructs the AssinafyClient to verify autoloading, credentials, and default transport without making an API request. Uses the sandbox base URL and prints the configured base URL. ```php getConfig()->getBaseUrl()}\n"; ``` -------------------------------- ### Start OAuth authorization and redirect Source: https://github.com/assinafy/php-sdk/blob/main/docs/EXAMPLES.md Mints a fresh verifier and state, stores the transaction in the session, and redirects the user to the authorization URL. ```php $start = $oauth->startAuthorization('https://app.example.com/integrations/assinafy/callback', [ OAuthResource::SCOPE_DOCUMENTS_READ, OAuthResource::SCOPE_DOCUMENTS_WRITE, OAuthResource::SCOPE_ACCOUNT_READ, OAuthResource::SCOPE_OPENID, OAuthResource::SCOPE_PROFILE, OAuthResource::SCOPE_EMAIL, OAuthResource::SCOPE_OFFLINE_ACCESS, ], ['issuer' => $server['issuer'], 'authorization_endpoint' => $server['authorization_endpoint']]); $_SESSION['assinafy_oauth'] = $start + ['created_at' => time()]; header('Location: ' . $start['authorization_url'], true, 302); exit; ``` -------------------------------- ### List templates usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/template-resource.md Shows how to list templates with a search filter and custom per-page value. ```php $page = $client->templates()->list(perPage: 20, filters: ['search' => 'agreement']); ``` -------------------------------- ### get() method signature Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/document-resource.md Defines the get method that retrieves a document by ID. Throws ValidationException for empty ID and ApiException 404 if the document does not exist. ```php /** * Retrieve a document, including its pages and current assignment. * `GET /documents/{document_id}` * * @return array * @throws ValidationException when `$documentId` is empty * @throws \Assinafy\SDK\Exceptions\ApiException 404 when the document does not exist */ public function get(string $documentId): array ``` -------------------------------- ### Start OAuth authorization with startAuthorization() Source: https://github.com/assinafy/php-sdk/blob/main/docs/OAUTH.md Call startAuthorization() to generate a PKCE verifier and state, then persist the transaction and redirect the user. The method makes no HTTP request. The options argument can override state, code_verifier, nonce, issuer, authorization_endpoint, and resource, but defaults are correct. A nonce is generated only when openid is among the scopes. If client_id or redirect_uri is wrong, the user is not redirected back; the authorization server shows an error page. ```php $start = $oauth->startAuthorization('https://app.example.com/integrations/assinafy/callback', [ OAuthResource::SCOPE_DOCUMENTS_READ, OAuthResource::SCOPE_DOCUMENTS_WRITE, OAuthResource::SCOPE_ACCOUNT_READ, OAuthResource::SCOPE_OPENID, OAuthResource::SCOPE_PROFILE, OAuthResource::SCOPE_EMAIL, OAuthResource::SCOPE_OFFLINE_ACCESS, ], ['issuer' => $server['issuer'], 'authorization_endpoint' => $server['authorization_endpoint']]); // [ // 'state' => '<43-character random string>', // 'code_verifier' => '<43-character random string>', // 'code_challenge' => '', // 'redirect_uri' => 'https://app.example.com/integrations/assinafy/callback', // 'issuer' => 'https://auth.assinafy.com.br', // 'resource' => 'https://api.assinafy.com.br', // 'nonce' => '<43-character random string>', // 'authorization_url' => 'https://auth.assinafy.com.br/oauth/authorize?response_type=code&…', // ] // The host application must already have started its secure authenticated session. $_SESSION['assinafy_oauth'] = $start + ['created_at' => time()]; header('Location: ' . $start['authorization_url'], true, 302); exit; ``` -------------------------------- ### Download template page usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/template-resource.md Shows how to download a rendered template page as JPEG bytes. ```php $jpeg = $client->templates()->downloadPage($templateId, $pageId); ``` -------------------------------- ### POST /v1/signers/identity-verification Source: https://github.com/assinafy/php-sdk/blob/main/docs/API_REFERENCE.md Starts an identity verification session. Requires the access code and a JSON body with `consent: true`. Only missing or expired sessions can be started. ```APIDOC ## POST /v1/signers/identity-verification ### Description Starts an identity verification session. Requires the access code and a JSON body with `consent: true`. Only missing or expired sessions can be started. ### Method POST ### Endpoint /v1/signers/identity-verification ### Parameters #### Query Parameters - **access_code** (string) - Required - The signer access code. #### Request Body - **consent** (boolean) - Required - Must be true. ### Request Example { "consent": true } ### Response #### Success Response (200) Returns the unwrapped `IdentityVerificationSession` object; the URL is a bearer link and must retain its fragment. #### Error Responses - **400** - Bad Request (existing live session) - **401** - Unauthorized - **500** - Internal Server Error ``` -------------------------------- ### exchangeCode() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/oauth-resource.md Exchanges the authorization code for tokens. The example stores the access token, refresh token, and workspace ID from the returned tokens array. ```php $tokens = $oauth->exchangeCode($code, $transaction); // store $tokens['access_token'], $tokens['refresh_token'] and the workspace ID ``` -------------------------------- ### GET /v1/users/self Source: https://github.com/assinafy/php-sdk/blob/main/docs/API_REFERENCE.md Retrieves the authenticated user's profile. The SDK method get() returns an unwrapped AuthUser object, normalizing differences between the OpenAPI and sandbox response structures. ```APIDOC ## GET /v1/users/self ### Description Retrieves the authenticated user's profile. The SDK method `get()` returns an unwrapped `AuthUser` object, normalizing differences between the OpenAPI and sandbox response structures. ### Method GET ### Endpoint /v1/users/self ### Parameters #### Query Parameters - **accessToken** (string) - Optional - Bearer token override; otherwise uses configured API-key or global-Bearer authentication. ### Response #### Success Response (200) - **AuthUser** (object) - The authenticated user's profile data. #### Response Example ```json { "data": { "id": "string", "email": "string", "name": "string" } } ``` ### Error Handling - **401** - Unauthorized - **500** - Internal Server Error ``` -------------------------------- ### Configuration::fromArray() Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/configuration.md Creates a Configuration instance from an associative array of configuration options. Accepts keys like api_key, account_id, base_url, timeout, connect_timeout, access_token, and webhook_secret. ```APIDOC ## Configuration::fromArray() ### Description Creates a Configuration instance from an array of configuration options. Throws \InvalidArgumentException for invalid credentials or timeouts. ### Method Static factory method ### Signature ```php public static function fromArray(#[\SensitiveParameter] array $config): self ``` ### Parameters #### Array Keys - **api_key** / **apiKey** (string) - Optional - Default: `''` - API key credential. - **account_id** / **accountId** (string) - Optional - Default: `''` - Account identifier. - **base_url** / **baseUrl** (string) - Optional - Default: `DEFAULT_BASE_URL` - Base URL for API requests. - **timeout** (int|numeric string) - Optional - Default: `30` - Request timeout in seconds. - **connect_timeout** / **connectTimeout** (int|numeric string) - Optional - Default: `10` - Connection timeout in seconds. - **access_token** / **accessToken** (string|null) - Optional - Default: `null` - Bearer access token. - **webhook_secret** (mixed) - Optional - Accepted and ignored. ### Exceptions - **\InvalidArgumentException** - Thrown for non-string credentials, non-positive/non-integer timeouts, or constructor rule violations. ### Example ```php $config = Configuration::fromArray(['api_key' => getenv('ASSINAFY_API_KEY'), 'account_id' => 'acct_1']); ``` ``` -------------------------------- ### list() usage example Source: https://github.com/assinafy/php-sdk/blob/main/_autodocs/api-reference/field-resource.md Lists all fields including the platform's standard signature, initial, and signatureDate fields. ```php $all = $client->fields()->list(includeStandard: true); ```