### Install Assinafy Go SDK v2 with go get Source: https://github.com/assinafy/golang-sdk/blob/main/README.md Use this command to install the Assinafy Go SDK v2. The module path is github.com/assinafy/golang-sdk/v2. ```bash go get github.com/assinafy/golang-sdk/v2 ``` -------------------------------- ### Get document example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-documents.md Example of using Get to fetch a document by ID. The example uses "doc-id" as a placeholder and logs a fatal error if the call fails. ```go doc, err := client.Documents.Get(ctx, "doc-id") if err != nil { log.Fatal(err) } ``` -------------------------------- ### StartCertificateSignature and CompleteCertificateSignature usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-signers.md Example of using the start/complete pair. The start call returns a token that is passed to the browser's Web PKI extension, which produces the signature. The complete call applies the signature and returns the signer name. ```go inicio, err := client.Signers.StartCertificateSignature(ctx, accessCode) if err != nil { log.Fatal(err) } // entrega inicio.Token à extensão Web PKI do navegador; ela produz a assinatura. resultado, err := client.Signers.CompleteCertificateSignature(ctx, accessCode, &models.CompleteCertificateSignatureRequest{Token: inicio.Token, Signature: assinaturaWebPKI}) fmt.Println("assinado por:", resultado.SignerName) ``` -------------------------------- ### Create usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-accounts.md Example of creating an account with name "Jurídico LTDA". Handles errors with log.Fatal. ```go conta, err := client.Accounts.Create(ctx, &models.CreateAccountRequest{Name: "Jurídico LTDA"}) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Download usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-signer-documents.md Example call to Download with artifact 'certificated', then writes the returned bytes to 'certificado.pdf'. ```go pdf, err := client.SignerDocuments.Download(ctx, signerID, docID, "certificated", accessCode) if err != nil { log.Fatal(err) } os.WriteFile("certificado.pdf", pdf, 0o644) ``` -------------------------------- ### SearchAll usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-signer-documents.md Example call to SearchAll with a search string 'contrato'. ```go docs, err := client.SignerDocuments.SearchAll(ctx, signerID, accessCode, "contrato") ``` -------------------------------- ### TOTP enrollment flow example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-users-authentication.md Starts TOTP enrollment, prompts for a 6-digit code, confirms enrollment, and prints the recovery codes. The secret and provisioning URI are shown only once. ```go enrol, err := client.Users.StartTOTPEnrollment(ctx, "meu celular") if err != nil { log.Fatal(err) } // Mostra enrol.Secret / enrol.ProvisioningURI como QR code; depois: codingo, _ := promptCode() // código de 6 dígitos do autenticador codigosRec, err := client.Users.ConfirmTOTPEnrollment(ctx, &models.ConfirmTOTPRequest{ ID: enrol.ID, Code: codingo, }) fmt.Println("guarde seus códigos de recuperação:", codigosRec) ``` -------------------------------- ### CreateFromTemplate usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-documents.md Example of creating a document from a template with a single signer and options like name, message, and tags. The accountID is passed as an empty string in this example. ```go doc, err := client.Documents.CreateFromTemplate(ctx, "", "template-id", []models.TemplateSigner{{RoleID: "role-1", ID: signerID}}, &models.CreateDocumentFromTemplateOptions{ Name: "NF-e 123", Message: "Assine por favor", Tags: []string{"fiscal"}, }) ``` -------------------------------- ### Get example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-public-documents.md Fetches public document info by ID and prints its name and page count. Returns an error for unknown or non-public documents (404, 500). ```go info, err := client.PublicDocuments.Get(ctx, "doc-id") if err != nil { log.Fatal(err) } fmt.Println(info.Name, "páginas:", info.PageCount) ``` -------------------------------- ### Create signer example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-signers.md Example of creating a signer with the Create method. Uses an empty accountID and a CreateSignerRequest with FullName and Email. ```go email := "ana@example.com" signer, err := client.Signers.Create(ctx, "", &models.CreateSignerRequest{ FullName: "Ana Souza", Email: &email, }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Example with validation and partial result cleanup Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/client.md Shows how to handle errors and clean up partial results when the upload fails after starting. It checks for ErrNoSigners and ErrInvalidSigner, and if a partial result exists, deletes the document and created signers. ```go expira := "2026-12-31T23:59:59Z" result, err := client.UploadAndRequestSignatures(ctx, pdf, "v2.pdf", signers, "", &expira, os.Getenv("ASSINAFY_ACCOUNT_ID")) if err != nil { if errors.Is(err, assinafy.ErrNoSigners) || errors.Is(err, assinafy.ErrInvalidSigner) { log.Fatalf("entrada inválida: %v", err) } if result != nil && result.Document != nil { // Limpa o documento já enviado e os signatários criados. _ = client.Documents.Delete(ctx, result.Document.ID) for _, sid := range result.SignerIDs { _ = client.Signers.Delete(ctx, "", sid) } } log.Fatalf("envio falhou após iniciar: %v", err) } ``` -------------------------------- ### CreateAPIKey usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-users-authentication.md Example of creating an API key. The returned key is shown only once, so it must be saved immediately. ```go res, err := client.Authentication.CreateAPIKey(ctx, &models.CreateAPIKeyRequest{Password: senha}) if err != nil { log.Fatal(err) } fmt.Println("nova chave:", *res.APIKey) // guarde agora ``` -------------------------------- ### Paginated listing example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-documents.md Example of using List with pagination. It fetches the first page with PerPage=50 and Status=StatusMetadataReady, then iterates through remaining pages. The example accumulates data across pages. ```go pagina, err := client.Documents.List(ctx, "", &models.ListParams{ PerPage: 50, Status: string(models.StatusMetadataReady), }) if err != nil { log.Fatal(err) } fmt.Printf("%d docs, %d páginas\n", len(pagina.Data), pagina.Pagination.PageCount) for pagina.Pagination.CurrentPage < pagina.Pagination.PageCount { pagina, err = client.Documents.List(ctx, "", &models.ListParams{Page: pagina.Pagination.CurrentPage + 1, PerPage: 50}) // acumula } ``` -------------------------------- ### Sign usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-assignments.md Example call to Sign with a list of SignDocumentItem values. ```go err := client.Assignments.Sign(ctx, docID, assignID, accessCode, []models.SignDocumentItem{ {ItemID: "item-1", FieldID: "field-1", PageID: "page-1", Value: "João da Silva"}, }) ``` -------------------------------- ### UserInfo usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/oauth.md Example of calling UserInfo and printing the subject, name, and email from the returned UserInfo. ```go info, err := cfg.UserInfo(ctx, token.AccessToken) if err != nil { log.Fatal(err) } fmt.Println(info.Sub, info.Name, info.Email) ``` -------------------------------- ### Login with 2FA verification example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-users-authentication.md Example of logging in and handling 2FA. If the result contains an MFAToken, the user must verify it within 5 minutes using VerifyMFA; otherwise, use the AccessToken. ```go resultado, err := client.Authentication.Login(ctx, &models.LoginRequest{Email: email, Password: senha}) if err != nil { log.Fatal(err) } if resultado.MFAToken != "" { // usuário tem 2FA: pede o código e completa o login resultado, err = client.Authentication.VerifyMFA(ctx, &models.VerifyMFARequest{ MFAToken: resultado.MFAToken, Code: codigo2FA, }) } usarToken(resultado.AccessToken) // ex.: NewClient(ClientOptions{Token: ...}) ``` -------------------------------- ### List usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-accounts.md Example of calling List and iterating over the returned accounts. Prints each account's ID, Name, and Roles. Handles errors with log.Fatal. ```go contas, err := client.Accounts.List(ctx) if err != nil { log.Fatal(err) } for _, c := range contas { fmt.Println(c.ID, c.Name, c.Roles) } ``` -------------------------------- ### ListStatuses usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-documents.md Example of calling ListStatuses via the client's Documents resource. ```go statuses, err := client.Documents.ListStatuses(ctx) ``` -------------------------------- ### DiscoverAuthorizationServer usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/oauth-metadata.md Shows how to call DiscoverAuthorizationServer with the default issuer and nil HTTP client, then create a config with the discovered endpoint. The example uses ellipses for ClientID and RedirectURI, which are not fully specified. ```go meta, err := oauth.DiscoverAuthorizationServer(ctx, oauth.DefaultIssuer, nil) if err != nil { log.Fatal(err) } cfg := &oauth.Config{Endpoint: meta.Endpoint(), ClientID: …, RedirectURI: …} ``` -------------------------------- ### DisplaySettings usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/types-field.md Shows how to instantiate DisplaySettings with concrete values. Use this in AssignmentField.DisplaySettings, TemplateFieldPlacement.DisplaySettings, or AssignmentItem.DisplaySettings. ```go pos := models.DisplaySettings{Left: 20, Top: 40, Width: 180, Height: 30, FontSize: 12} ``` -------------------------------- ### Latest usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/oauth-tokensource.md Example of using Latest to persist the token during shutdown. It checks for errors and saves the token only when saved is false. ```go token, saved, err := source.Latest(ctx) if err != nil { return err } if !saved { return db.SaveToken(ctx, token.RefreshToken, token.Expiry) } ``` -------------------------------- ### GetCurrent usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-signer-documents.md Example call to GetCurrent with a signer ID and access code. ```go doc, err := client.SignerDocuments.GetCurrent(ctx, signerID, accessCode) ``` -------------------------------- ### Usage example for GetSigningInfo Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-assignments.md Example call to GetSigningInfo using an access code, then prints the document status and the current signer's full name. ```go doc, err := client.Assignments.GetSigningInfo(ctx, accessCode) fmt.Println("status:", doc.Status, "signatário atual:", doc.CurrentSigner.FullName) ``` -------------------------------- ### ListEventTypes usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-webhooks.md Example of calling ListEventTypes and iterating over the returned event types. ```go tipos, err := client.Webhooks.ListEventTypes(ctx) for _, t := range tipos { fmt.Println(t.ID, t.Description) } ``` -------------------------------- ### Create field example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-templates-tags-fields.md Example of creating a text field definition with name 'CNPJ do cliente'. Uses the Create method with an empty accountID (likely from the client's context). ```go field, err := client.Fields.Create(ctx, "", &models.CreateFieldDefinitionRequest{ Type: "text", Name: "CNPJ do cliente", }) ``` -------------------------------- ### SocialLoginURL usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-users-authentication.md Example of generating a social login URL and redirecting the user's browser to it. ```go url := client.Authentication.SocialLoginURL("google") http.Redirect(w, r, url, http.StatusFound) ``` -------------------------------- ### Example: Using InsufficientScope Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/errors.md Example usage of InsufficientScope to check for insufficient scope and redirect the user to authorization with the required scope. ```go if scope, ok := sdkerrors.InsufficientScope(err); ok { // Reenvie o usuário pelo fluxo de autorização com scope adicionado. return redirectToAuthorization(scope) } ``` -------------------------------- ### Identity review usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-assignments.md Example workflow: fetch identity review, check if InReview and evidence available, then approve. Approval releases certification when all sign; rejection cancels document and notifies. Errors: 400, 401, 404, 500. ```go revisao, err := client.Assignments.GetIdentityReview(ctx, docID, assignID, signerID) if err != nil { log.Fatal(err) } if revisao.Status == "InReview" && revisao.EvidenceAvailable { decidida, err := client.Assignments.DecideIdentityReview(ctx, docID, assignID, signerID, &models.DecideIdentityReviewRequest{Decision: models.IdentityReviewDecisionApproved}) if err != nil { log.Fatal(err) } fmt.Println("revisada por:", decidida.ReviewedBy.Name) } ``` -------------------------------- ### Verify usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-documents.md Example of verifying a document using a signature hash. Prints whether the document is valid. Unknown or malformed hashes are represented by the verification payload or an API error. ```go res, err := client.Documents.Verify(ctx, "sha256:…") if err != nil { log.Fatal(err) } fmt.Println("válido:", res.IsValid) ``` -------------------------------- ### DownloadPage usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-documents.md Example of calling DownloadPage to fetch a page's binary data. The pageID is obtained from a document's Pages collection. ```go pg, err := client.Documents.DownloadPage(ctx, "doc-id", pagina.ID) // pagina de doc.Pages ``` -------------------------------- ### ListAsWorkspace usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-signer-documents.md Example call to ListAsWorkspace with PerPage set to 50. Uses the client's API key/bearer instead of a signer access code. ```go pagina, err := client.SignerDocuments.ListAsWorkspace(ctx, signerID, &models.ListParams{PerPage: 50}) ``` -------------------------------- ### SignMultiple usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-signer-documents.md Example call to SignMultiple with two document IDs. A 400 error occurs if any document is not eligible. ```go if err := client.SignerDocuments.SignMultiple(ctx, accessCode, []string{"d1", "d2"}); err != nil { // 400 se algum documento não é elegível } ``` -------------------------------- ### DiscoverProtectedResource usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/oauth-metadata.md Example of calling DiscoverProtectedResource with an empty apiRoot (uses DefaultResource) and nil HTTP client. It prints the resource and issuer. The issuer is obtained from the first AuthorizationServers. ```go meta, err := oauth.DiscoverProtectedResource(ctx, "", nil) if err != nil { log.Fatal(err) } issuer, _ := meta.Issuer, meta.AuthorizationServers fmt.Println("recurso:", meta.Resource, "issuer:", meta.Issuer()) ``` -------------------------------- ### Refresh usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/oauth.md Example of calling Refresh and handling errors, especially ErrRefreshIndeterminate. Never resend the token that was sent; only proceed with a different saved token. ```go novo, err := cfg.Refresh(ctx, token.RefreshToken) if err != nil { if errors.Is(err, oauth.ErrRefreshIndeterminate) { // leia o token salvo de novo; só prossiga se for outro (salvo depois) return reconnectUser() } return err } saveToken(novo) ``` -------------------------------- ### POST /signers/certificate/start Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/endpoints.md Starts a certificate-based signature process. Requires signer authentication. ```APIDOC ## POST /signers/certificate/start ### Description Starts a certificate-based signature process. ### Method POST ### Endpoint `/signers/certificate/start` ### Response #### Success Response (200) - **data** (object) - Contains a token. - **token** (string) - The token for the certificate signature process. #### Response Example ```json { "data": { "token": "token_value" } } ``` ### Errors - 400 - Bad Request - 401 - Unauthorized - 500 - Internal Server Error ``` -------------------------------- ### CreateEndpoint usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-webhooks.md Example call to CreateEndpoint with a webhook URL, email, events, and SigningEnabled true. The returned endpoint contains a Secret that is shown only once; store it securely. Requires OAuth scope webhooks:write. ```go endpoint, err := client.Webhooks.CreateEndpoint(ctx, "", &models.CreateWebhookEndpointRequest{ URL: "https://meuapp.example/webhook", Email: "ops@example.com", Events: []string{"document.completed", "document.rejected"}, SigningEnabled: true, }) if err != nil { log.Fatal(err) } secret := endpoint.Secret // única exibição ``` -------------------------------- ### Quickstart: List accounts with Assinafy Go SDK Source: https://github.com/assinafy/golang-sdk/blob/main/README.md A complete Go program that creates a client with credentials from environment variables and lists accounts against the sandbox. It uses assinafy.SandboxBaseURL and prints the number of accounts. Credentials should be kept in environment variables, never in source code. ```go package main import ( "context" "fmt" "log" "os" assinafy "github.com/assinafy/golang-sdk/v2" ) func main() { client, err := assinafy.NewClient(assinafy.ClientOptions{ APIKey: os.Getenv("ASSINAFY_API_KEY"), AccountID: os.Getenv("ASSINAFY_ACCOUNT_ID"), BaseURL: assinafy.SandboxBaseURL, }) if err != nil { log.Fatal(err) } contas, err := client.Accounts.List(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("contas: %d\n", len(contas)) } ``` -------------------------------- ### Basic NewClient example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/client.md Creates a client using API key and account ID from environment variables. Logs fatal error if construction fails. ```go client, err := assinafy.NewClient(assinafy.ClientOptions{ APIKey: os.Getenv("ASSINAFY_API_KEY"), AccountID: os.Getenv("ASSINAFY_ACCOUNT_ID"), }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Step 1: Initiate OAuth connection with PKCE and state Source: https://github.com/assinafy/golang-sdk/blob/main/README.md Generates a PKCE pair and state, builds the authorization URL, and redirects the user's browser. Requires ASSINAFY_CLIENT_ID and optionally ASSINAFY_CLIENT_SECRET for confidential apps. Store pkce.Verifier and state in the user's session before redirecting. ```go config := &oauth.Config{ ClientID: os.Getenv("ASSINAFY_CLIENT_ID"), ClientSecret: os.Getenv("ASSINAFY_CLIENT_SECRET"), // omita numa aplicação pública RedirectURI: "https://meuapp.example/oauth/callback", Scopes: []string{ oauth.ScopeAccountRead, oauth.ScopeDocumentsRead, oauth.ScopeDocumentsWrite, oauth.ScopeOfflineAccess, }, } pkce, err := oauth.NewPKCE() if err != nil { return err } state, err := oauth.NewState() if err != nil { return err } // Guarde pkce.Verifier e state na sessão deste usuário. authorizeURL, err := config.AuthorizationURL(oauth.AuthorizationRequest{ State: state, CodeChallenge: pkce.Challenge, }) if err != nil { return err } http.Redirect(w, r, authorizeURL, http.StatusFound) ``` -------------------------------- ### Complete Go program: PDF to signed document with Assinafy SDK Source: https://github.com/assinafy/golang-sdk/blob/main/README.md Run this program as main.go with environment variables ASSINAFY_API_KEY, ASSINAFY_ACCOUNT_ID, ASSINAFY_PDF_PATH, ASSINAFY_SIGNER_NAME, and ASSINAFY_SIGNER_EMAIL set. It sends a real email invitation in the sandbox and waits up to 30 minutes for the signer. The program polls every 5 seconds and saves the certified document as 'agreement-signed.pdf'. ```go package main import ( "context" "fmt" "log" "os" "time" assinafy "github.com/assinafy/golang-sdk/v2" "github.com/assinafy/golang-sdk/v2/models" ) func main() { for _, key := range []string{"ASSINAFY_API_KEY", "ASSINAFY_ACCOUNT_ID", "ASSINAFY_PDF_PATH", "ASSINAFY_SIGNER_NAME", "ASSINAFY_SIGNER_EMAIL"} { if os.Getenv(key) == "" { log.Fatalf("set %s before running this program", key) } } client, err := assinafy.NewClient(assinafy.ClientOptions{ APIKey: os.Getenv("ASSINAFY_API_KEY"), AccountID: os.Getenv("ASSINAFY_ACCOUNT_ID"), BaseURL: assinafy.SandboxBaseURL, }) if err != nil { log.Fatal(err) } ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) defer cancel() pdf, err := os.ReadFile(os.Getenv("ASSINAFY_PDF_PATH")) if err != nil { log.Fatal(err) } document, err := client.Documents.Upload(ctx, "", pdf, "agreement.pdf", nil) if err != nil { log.Fatal(err) } fmt.Printf("document: %s\n", document.ID) email := os.Getenv("ASSINAFY_SIGNER_EMAIL") signer, err := client.Signers.Create(ctx, "", &models.CreateSignerRequest{ FullName: os.Getenv("ASSINAFY_SIGNER_NAME"), Email: &email, }) if err != nil { log.Fatal(err) } fmt.Printf("signer: %s\n", signer.ID) estimate, err := client.Assignments.EstimateCostWithRequest(ctx, document.ID, &models.EstimateAssignmentCostRequest{ Method: models.MethodVirtual, Signers: []models.EstimateAssignmentCostSigner{{VerificationMethod: models.VerificationMethodEmail}}, }) if err != nil { log.Fatal(err) } if !estimate.HasSufficientResources { log.Fatalf("cannot send: %v", estimate.Message) } assignment, err := client.Assignments.Create(ctx, document.ID, &models.CreateAssignmentRequest{ Method: models.MethodVirtual, Signers: []models.SignerReference{{ ID: signer.ID, VerificationMethod: models.VerificationMethodEmail, NotificationMethods: []string{models.NotificationMethodEmail}, }}, }) if err != nil { log.Fatal(err) } fmt.Printf("assignment: %s; waiting for the signer\n", assignment.ID) ticker := time.NewTicker(5 * time.Second) defer ticker.Stop() for { document, err = client.Documents.Get(ctx, document.ID) if err != nil { log.Fatal(err) } switch document.Status { case models.StatusCertificated: certified, err := client.Documents.Download(ctx, document.ID, "certificated") if err != nil { log.Fatal(err) } if err := os.WriteFile("agreement-signed.pdf", certified, 0o600); err != nil { log.Fatal(err) } fmt.Println("saved agreement-signed.pdf") return case models.StatusExpired, models.StatusRejectedBySigner, models.StatusRejectedByUser, models.StatusFailed: log.Fatalf("signing ended with status %q", document.Status) } select { case <-ctx.Done(): log.Fatal(ctx.Err()) case <-ticker.C: } } } ``` -------------------------------- ### Creating PKCE and state Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/oauth.md Shows how to create a new PKCE pair and a new state using the SDK functions. Handle errors from both calls. ```go pkce, err := oauth.NewPKCE() if err != nil { return err } state, err := oauth.NewState() if err != nil { return err } ``` -------------------------------- ### Get Subscription Source: https://github.com/assinafy/golang-sdk/blob/main/README.md Gets the subscription for the oldest endpoint. Intended for accounts with a single endpoint. ```APIDOC ## Get Subscription ### Description Gets the subscription for the oldest endpoint. Intended for accounts with a single endpoint. ### Method GET ### Endpoint `client.Webhooks.GetSubscription` ### Parameters None ### Response #### Success Response (200) - **subscription** (object) - The subscription object. ``` -------------------------------- ### Get and GetDocument method signatures Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-public-documents.md Get is deprecated; use GetDocument when the deployment returns the full Document shape. Get returns a reduced public projection, while GetDocument returns the full Document shape. ```go // GET /public/documents/{document_id}. // Deprecated: use GetDocument when the deployment returns the full Document shape. func (r *PublicDocumentResource) Get(ctx context.Context, documentID string) (*models.PublicDocumentInfo, error) func (r *PublicDocumentResource) GetDocument(ctx context.Context, documentID string) (*models.Document, error) ``` -------------------------------- ### RetryDispatch usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-webhooks.md Example of calling RetryDispatch with an empty account ID and a dispatch ID. ```go d, err := client.Webhooks.RetryDispatch(ctx, "", dispatch.ID) ``` -------------------------------- ### Upload example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-documents.md Reads a PDF file and uploads it, then prints the document ID and status. Requires a valid PDF file. ```go pdf, _ := os.ReadFile("contrato.pdf") doc, err := client.Documents.Upload(ctx, "", pdf, "contrato.pdf", nil) if err != nil { log.Fatal(err) } fmt.Println(doc.ID, doc.Status) ``` -------------------------------- ### Template Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/types-template.md Models GET /accounts/{id}/templates and GET /accounts/{id}/templates/{tid}. ```APIDOC ## Template ### Description Models GET /accounts/{id}/templates and GET /accounts/{id}/templates/{tid}. ### Fields - `Resource` (string) - Optional - Discriminador quando presente. - `ID` (string) - Required - Identificador do template. - `Name` (string) - Required - Nome de exibição. - `DocumentName` (*string) - Optional - Nome padrão para documentos gerados. - `Message` (*string) - Optional - Mensagem padrão de convite. - `Status` (TemplateStatus) - Required - Código do ciclo de vida. - `Pages` ([]TemplatePage) - Optional - Páginas renderizadas e posicionamentos quando incluídos. - `Roles` ([]TemplateRole) - Required - Papéis de assinatura exigidos. - `Tags` ([]Tag) - Required (sempre presente, possivelmente vazio) - Etiquetas do template; inline só `ID`/`Name`. - `DefaultDocumentTags` ([]Tag) - Optional - Aplicadas a todo documento criado; só o endpoint de detalhe popula. - `CreatedAt` / `UpdatedAt` (Timestamp) - Required - Criação/atualização. ``` -------------------------------- ### Step 3: Discover account and call API with token source Source: https://github.com/assinafy/golang-sdk/blob/main/README.md Creates a token source that renews access tokens, initializes the client, lists the user's account (exactly one), and re-initializes the client with the account ID. Access tokens last one hour; refresh tokens last 30 days and are renewed on each refresh. ```go source := oauth.NewTokenSource(config, token, func(renewed *oauth.Token) error { return store.SaveTokens(userID, renewed) // antes de o novo token de acesso ser usado }) client, err := assinafy.NewClient(assinafy.ClientOptions{TokenSource: source}) if err != nil { return err } workspaces, err := client.Accounts.List(ctx) if err != nil { return err } if len(workspaces) != 1 { return fmt.Errorf("OAuth connection must identify exactly one workspace") } client, err = assinafy.NewClient(assinafy.ClientOptions{ TokenSource: source, AccountID: workspaces[0].ID, }) if err != nil { return err } ``` -------------------------------- ### Creating authorization URL with PKCE Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/oauth.md Example of generating a PKCE challenge and state, then building the authorization URL. The code challenge is required for the request. ```go pkce, _ := oauth.NewPKCE() state, _ := oauth.NewState() authURL, err := cfg.AuthorizationURL(oauth.AuthorizationRequest{ State: state, CodeChallenge: pkce.Challenge, }) ``` -------------------------------- ### IsStatusCode usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/errors.md Example usage of IsStatusCode to check for a 404 Not Found error and log a message. ```go if sdkerrors.IsStatusCode(err, http.StatusNotFound) { log.Println("recurso não encontrado") } ``` -------------------------------- ### StartIdentityVerification usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-signers.md Shows how to call StartIdentityVerification with a consent request. The returned session URL must be opened as-is, including the fragment, and never logged. ```go sessao, err := client.Signers.StartIdentityVerification(ctx, accessCode, &models.StartIdentityVerificationRequest{Consent: true}) if err != nil { log.Fatal(err) } // sessao.URL — abra como está, incluindo o fragmento; nunca registre. ``` -------------------------------- ### Create document from template with signers and options Source: https://github.com/assinafy/golang-sdk/blob/main/README.md Lists templates, gets a template's details, estimates cost, and creates a document from a template. Requires existing signers and a template created in the Assinafy web app. Provide one TemplateSigner per role; options include name and tags. ```go templates, err := client.Templates.List(ctx, "", nil) template, err := client.Templates.Get(ctx, "", templates.Data[0].ID) // papéis, páginas, etiquetas padrão estimate, err := client.Documents.EstimateCostFromTemplate(ctx, "", template.ID, []models.TemplateSigner{{RoleID: template.Roles[0].ID, VerificationMethod: models.VerificationMethodEmail}}) document, err := client.Documents.CreateFromTemplate(ctx, "", template.ID, []models.TemplateSigner{{RoleID: template.Roles[0].ID, ID: signer.ID}}, &models.CreateDocumentFromTemplateOptions{ Name: "Contrato da Exemplo Ltda", Tags: []string{"contratos"}, }) ``` -------------------------------- ### Get Field Definition Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-templates-tags-fields.md Retrieves a specific field definition. Corresponds to GET /accounts/{account_id}/fields/{field_id}. ```APIDOC ## GET /accounts/{account_id}/fields/{field_id} ### Description Retrieves a specific 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. ### Response #### Success Response (200) - **FieldDefinition** (object) - The requested field definition. #### Response Example ```json { "id": "field-id", "type": "text", "name": "CNPJ do cliente" } ``` ### Errors - 400, 401, 404, 500 ``` -------------------------------- ### Error Inspection Example Source: https://github.com/assinafy/golang-sdk/blob/main/README.md Example showing how to inspect errors from SDK calls using the provided error types and helpers. ```APIDOC ## Error Inspection Example ### Description Demonstrates how to inspect errors returned by SDK methods, distinguishing between API errors, network errors, retryable failures, and local validation errors. ### Code Example ```go document, err := client.Documents.Get(ctx, documentID) var apiErr *sdkerrors.APIError switch { case sdkerrors.IsStatusCode(err, http.StatusNotFound): // o documento não existe case stderrors.As(err, &apiErr): // qualquer outra resposta: apiErr.StatusCode, .Message, .Data, .Headers, .Restrictions case sdkerrors.IsRetryable(err): // 429, 5xx ou falha de transporte — repita com backoff case stderrors.Is(err, sdkerrors.ErrInvalidInput): // rejeitado localmente, antes de qualquer requisição } ``` ### Error Types - **`*errors.APIError`** — Represents an HTTP response or unsuccessful envelope status. Contains `StatusCode`, `Message`, optional `Data`, response `Headers` (including `Retry-After`), and account exclusion `Restrictions`. Use `apiErr.RateLimit()` to read `X-Rate-Limit-Limit`, `X-Rate-Limit-Remaining`, `X-Rate-Limit-Reset`, and on 429, `Retry-After`. - **`*errors.NetworkError`** — Represents a transport failure. Any `signer-access-code` in the URL is hidden before the error is returned. - **`errors.ErrInvalidInput`** — Local rejection: empty required ID, non-PDF upload, file too large, malformed deadline. - **`errors.ErrDigitalCertificateRequiresVirtual`** — Stable local rejection for a `DigitalCertificate` signer in a non-virtual assignment. Also matches `errors.ErrInvalidInput`. ### Helper Functions - **`errors.InsufficientScope(err)`** — Reads the scope named by a `403` with `insufficient_scope` on OAuth connections. - **`oauth.ErrorCode(err)`** — Reads the RFC 6749 code from an `*oauth.Error` returned by the `oauth` package. - **`errors.IsRetryable(err)`** — Returns `true` for HTTP 429, 5xx, and transport failures; `false` for canceled contexts and refused redirects. ### Retry Policy The SDK does not retry anything on its own. Retry policy, backoff, and idempotency are the caller's responsibility. Many operations send email or consume credits. ### Redirect Safety - **`errors.ErrUnsafeRedirect`** — Wraps a cross-origin redirect that the SDK refused to follow for a request with a body or non-idempotent method. - Read-only cross-origin redirects are followed with the API key, bearer token, and signer access code removed. ``` -------------------------------- ### Tipos para assinatura com certificado digital (Web PKI) Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/types-signer.md Estruturas usadas no fluxo de assinatura com certificado digital via Web PKI. O token de StartCertificateSignatureResult é enviado à extensão do navegador; o resultado assinado é enviado em CompleteCertificateSignatureRequest. Signature é opcional e Extra adiciona campos arbitrários que sobrescrevem Token/Signature. O contrato não é publicado e pode mudar sem aviso. ```go type StartCertificateSignatureResult struct { Token string `json:"token"` } type CompleteCertificateSignatureRequest struct { Token string `json:"token"` Signature string `json:"signature,omitempty"` Extra map[string]any `json:"-"` } type CompleteCertificateSignatureResult struct { SignerName string `json:"signerName"` } ``` -------------------------------- ### Using TokenSource with OAuth Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/client.md Shows how to create a TokenSource using oauth.NewTokenSource and pass it to assinafy.NewClient via ClientOptions. Requires a config, token, and saveToken callback. ```go source := oauth.NewTokenSource(cfg, token, saveToken) client, err := assinafy.NewClient(assinafy.ClientOptions{ TokenSource: source, AccountID: workspaceID, }) ``` -------------------------------- ### Get method signature Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-documents.md Method signature for Get. Retrieves a single document by its ID from /documents/{document_id}. Returns an authenticated document. ```go // GET /documents/{document_id}. func (r *DocumentResource) Get(ctx context.Context, documentID string) (*models.Document, error) ``` -------------------------------- ### Development Commands for Build, Test, Vet, Format, Coverage, Lint, and Vulnerability Check Source: https://github.com/assinafy/golang-sdk/blob/main/README.md Run these commands to build, test with race detection and coverage, vet, check formatting, view coverage, run golangci-lint, and check for vulnerabilities. The GitHub Actions CI runs the same checks plus govulncheck and a coverage floor. ```bash go build ./... go test -race -count=1 -covermode=atomic -coverprofile=coverage.out ./... go vet ./... gofmt -l . go tool cover -func=coverage.out go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.13.2 run --timeout=5m go run golang.org/x/vuln/cmd/govulncheck@v1.7.0 -test ./... ``` -------------------------------- ### ListFieldDefinitionsParams struct for GET /accounts/{id}/fields Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/types-field.md Defines the query parameters include_inactive and include_standard for the GET /accounts/{id}/fields endpoint. ```go type ListFieldDefinitionsParams struct { IncludeInactive bool IncludeStandard bool } ``` -------------------------------- ### ValidateAuthenticated usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-templates-tags-fields.md Example of validating a field value (CNPJ) using ValidateAuthenticated. Checks the Success flag and prints an error message if invalid. ```go res, err := client.Fields.ValidateAuthenticated(ctx, "", "field-id", &models.ValidateFieldRequest{Value: "12.345.678/0001-90"}) if !res.Success { fmt.Println("inválido:", res.ErrorMessage) } ``` -------------------------------- ### Get / GetDocument Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-public-documents.md Retrieves a public document by ID. Get is deprecated; use GetDocument for the full Document shape. Returns PublicDocumentInfo or Document respectively. ```APIDOC ## [GET] /public/documents/{document_id} ### Description Retrieves a public document by its ID. The `Get` method returns a reduced public projection (`PublicDocumentInfo`), while `GetDocument` returns the full public `Document` shape. No authentication is required. ### Method GET ### Endpoint /public/documents/{document_id} ### Parameters #### Path Parameters - **document_id** (string) - Required - The unique identifier of the document. ### Response #### Success Response (200) - **Get** returns `*models.PublicDocumentInfo` with fields: `resource`, `id`, `name`, `page_count`, `created_by`. `page_count` accepts integer or string in JSON. - **GetDocument** returns `*models.Document` with the public documented shape; deployments with reduced shape populate only corresponding fields. #### Response Example ```json { "resource": "document", "id": "doc-id", "name": "Contract.pdf", "page_count": 3, "created_by": "user@example.com" } ``` ### Error Handling - **404** - Document not found or not public. - **500** - Internal server error. ### Code Example ```go info, err := client.PublicDocuments.Get(ctx, "doc-id") if err != nil { log.Fatal(err) } fmt.Println(info.Name, "páginas:", info.PageCount) ``` ``` -------------------------------- ### NewClient with OAuth token source and sandbox Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/client.md Creates a client using an OAuth token source, sandbox base URL, and custom timeout. The token source persists rotated refresh tokens. ```go source := oauth.NewTokenSource(cfg, token, func(t *oauth.Token) error { return saveTokenToDatabase(t) // persiste o refresh token rotacionado }) client, err := assinafy.NewClient(assinafy.ClientOptions{ TokenSource: source, AccountID: os.Getenv("ASSINAFY_WORKSPACE_ID"), BaseURL: assinafy.SandboxBaseURL, Timeout: 15 * time.Second, }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Import the Assinafy Go SDK Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/client.md Shows how to import the root package of the Assinafy Go SDK. ```APIDOC ## Import the Assinafy Go SDK ### Description Import the root package of the Assinafy Go SDK to access the Client and related types. ### Code Example ```go import assinafy "github.com/assinafy/golang-sdk/v2" ``` ``` -------------------------------- ### Conduzir sessão do signatário com código de acesso Source: https://github.com/assinafy/golang-sdk/blob/main/README.md Executa as etapas da sessão do signatário quando a aplicação hospeda a experiência: obter informações de assinatura, verificar identidade, confirmar dados, aceitar termos, enviar assinatura e assinar. Cada método envia apenas o código de acesso, nunca a chave de API ou token bearer, e rejeita código vazio com errors.ErrInvalidInput. ```go document, err := client.Assignments.GetSigningInfo(ctx, signerAccessCode) // GET /sign signer, err := client.Signers.GetSelf(ctx, signerAccessCode) // quem está assinando err = client.Signers.VerifyEmail(ctx, signerAccessCode, otp) // código de uso único _, err = client.Signers.ConfirmDataAndGet(ctx, documentID, signerAccessCode, body) // confirma os dados err = client.Signers.AcceptTermsOnly(ctx, signerAccessCode) // aceita os termos err = client.Signers.UploadSignatureWithReuse(ctx, signerAccessCode, "signature", true, pngBytes) err = client.Assignments.Sign(ctx, documentID, assignmentID, signerAccessCode, items) ``` -------------------------------- ### GetEndpointSecret usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-webhooks.md Example of retrieving the endpoint secret and creating a webhook verifier with assinafy.NewWebhookVerifier. The secret is a Standard Webhooks signing secret (whsec_ + base64). ```go secret, err := client.Webhooks.GetEndpointSecret(ctx, "", "endpoint-id") if err != nil { log.Fatal(err) } verifier := assinafy.NewWebhookVerifier(secret) // veja webhook-verifier.md ``` -------------------------------- ### Estrutura do tipo Client Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/client.md Define o ponto de entrada top-level do SDK, agrupando clientes por recurso. Criado apenas por NewClient; não há valor zero utilizável. Campos de recurso são ponteiros para clientes tipados do pacote resources. ```go type Client struct { // campos não exportados accountID string Accounts *resources.AccountResource Documents *resources.DocumentResource Signers *resources.SignerResource SignerDocuments *resources.SignerDocumentResource Assignments *resources.AssignmentResource Webhooks *resources.WebhookResource Templates *resources.TemplateResource Tags *resources.TagResource Fields *resources.FieldResource Users *resources.UserResource Authentication *resources.AuthenticationResource PublicDocuments *resources.PublicDocumentResource } ``` -------------------------------- ### Signers.List, Get, Update, Delete Source: https://github.com/assinafy/golang-sdk/blob/main/README.md Completes the signer management operations: list all signers, get a signer by ID, update signer details, and delete a signer. ```APIDOC ## Signers.List, Get, Update, Delete ### Description Completes the signer management operations: list all signers, get a signer by ID, update signer details, and delete a signer. ### Methods - **List** - Lists signers. - **Get** - Gets a signer by ID. - **Update** - Updates signer details (including GovernmentID). - **Delete** - Deletes a signer. ### Parameters - **ctx** (context.Context) - Required - Context for cancellation and deadlines. - **accountID** (string) - Optional - Account ID; empty uses ClientOptions.AccountID. - **request** (varies) - Required for Create/Update; optional for List/Get/Delete. ### Response List returns a paginated result or slice; Get/Update return a *models.Signer; Delete returns success. ``` -------------------------------- ### ValidateMultipleAuthenticated usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/types-field.md Shows how to call ValidateMultipleAuthenticated with a slice of ValidateMultipleFieldsRequest and print the validation results. The example uses field IDs 'field-1' and 'field-2' with sample values. ```go res, err := client.Fields.ValidateMultipleAuthenticated(ctx, "", []models.ValidateMultipleFieldsRequest{ {FieldID: "field-1", Value: "12.345.678/0001-90"}, {FieldID: "field-2", Value: "2026-10-01"}, }) for _, r := range res { fmt.Printf("%s: success=%t msg=%s\n", r.FieldID, r.Success, r.ErrorMessage) } ``` -------------------------------- ### UpdateEndpoint usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-webhooks.md Example call to UpdateEndpoint to change the events list for an existing endpoint. Only non-nil fields are updated. Requires OAuth scope webhooks:write. ```go err := client.Webhooks.UpdateEndpoint(ctx, "", "endpoint-id", &models.UpdateWebhookEndpointRequest{ Events: []string{"document.completed"}, }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Importar pacote assinafy Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/client.md Importa o pacote raiz do SDK Go da Assinafy com o alias 'assinafy'. ```go import assinafy "github.com/assinafy/golang-sdk/v2" ``` -------------------------------- ### EstimateCostWithRequest usage example Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/resources-assignments.md Example of calling EstimateCostWithRequest to estimate cost without creating the assignment. Checks HasSufficientResources and logs fatal error with BlockingReason and Message if insufficient. ```go custo, err := client.Assignments.EstimateCostWithRequest(ctx, docID, &models.EstimateAssignmentCostRequest{ Method: models.MethodVirtual, Signers: []models.EstimateAssignmentCostSigner{ {VerificationMethod: models.VerificationMethodWhatsApp, NotificationMethods: []string{models.NotificationMethodWhatsApp}}, }, }) if err != nil { log.Fatal(err) } if !custo.HasSufficientResources { log.Fatalf("impossível enviar: %v (%v)", custo.BlockingReason, custo.Message) } ``` -------------------------------- ### Método (*APIError) RateLimit() Source: https://github.com/assinafy/golang-sdk/blob/main/_autodocs/api-reference/errors.md Lê as cotas dos cabeçalhos X-Rate-Limit-* e Retry-After da resposta falha. Em 429, espere RetryAfter antes de reenviar. ```go func (e *APIError) RateLimit() RateLimit ```