velix

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 3, 2026 License: MIT Imports: 9 Imported by: 0

README

velix-sdk-go — Go SDK version

⚠️ Alpha / pre-release. This SDK targets a public API surface that does not yet fully exist on the VELIX backend (see internal task #593). Endpoints and auth may not work against production. Do not use in production integrations yet.

Official Go SDK for the VELIX Biometrics platform — facial access control B2B SaaS.

Requirements

  • Go 1.22+
  • Zero external dependencies (stdlib only)

Installation

go get github.com/VELIX-Biometrics/sdk-velix-go

Quick Start

package main

import (
    "context"
    "fmt"
    velix "github.com/VELIX-Biometrics/sdk-velix-go"
)

func main() {
    client := velix.NewClient(velix.Config{
        APIURL: "https://api.velixbiometrics.com",
        APIKey: "vx_live_...",
    })

    result, err := client.Checkin.Facial(context.Background(), "tenant-slug", frameBase64)
    if err != nil {
        panic(err)
    }
    fmt.Println(result.Passed, result.PersonID)
}

Environment Variables

Variable Required Description
VELIX_API_URL Yes API base URL (https://api.velixbiometrics.com)
VELIX_API_KEY Yes Tenant API key (vx_live_... or vx_sandbox_...)
client := velix.NewClient(velix.Config{
    APIURL: os.Getenv("VELIX_API_URL"),
    APIKey: os.Getenv("VELIX_API_KEY"),
})

Modules

Module Methods
client.Checkin Facial(), QR(), PIN(), GetHistory()
client.Persons List(), Get(), Create(), Update(), Delete(), Enroll()
client.Events List(), Get(), Create(), Configure()
client.Tenants Me(), UpdateSettings()

Checkin Module

ctx := context.Background()

// Facial identification (base64 JPEG frame)
result, err := client.Checkin.Facial(ctx, "tenant-slug", frameBase64)
// result.Passed == true
// result.PersonID == "uuid"
// result.PersonName == "João Silva"

// QR code checkin
result, err := client.Checkin.QR(ctx, "tenant-slug", qrToken)

// PIN checkin
result, err := client.Checkin.PIN(ctx, "tenant-slug", pin)

// Paginated history
history, err := client.Checkin.GetHistory(ctx, "tenant-slug", &velix.ListOptions{Page: 1, Limit: 20})

Persons Module

// List with optional search
list, err := client.Persons.List(ctx, &velix.ListOptions{Page: 1, Limit: 20, Search: "João"})

// Get by ID
person, err := client.Persons.Get(ctx, "uuid")

// Create
created, err := client.Persons.Create(ctx, velix.CreatePersonInput{
    Name:       "João Silva",
    Email:      "joao@company.com",
    ExternalID: "EMP-001",
})

// Update
err = client.Persons.Update(ctx, "uuid", velix.UpdatePersonInput{Name: "João B. Silva"})

// Enroll biometrics (minimum 3 base64 frames)
err = client.Persons.Enroll(ctx, "uuid", []string{frame1, frame2, frame3})

// Delete
err = client.Persons.Delete(ctx, "uuid")

Events Module

list,    err := client.Events.List(ctx, &velix.ListOptions{Page: 1, Limit: 20})
event,   err := client.Events.Get(ctx, "uuid")
created, err := client.Events.Create(ctx, velix.CreateEventInput{Name: "Conference 2026"})
err = client.Events.Configure(ctx, "uuid", velix.EventConfig{CheckInOpen: true})

Tenants Module

tenant, err := client.Tenants.Me(ctx)
err = client.Tenants.UpdateSettings(ctx, velix.TenantSettings{RequireLiveness: true})

Error Handling

import "errors"

result, err := client.Checkin.Facial(ctx, "slug", frame)
if err != nil {
    var authErr *velix.AuthError
    var bioErr  *velix.BiometricError
    var rlErr   *velix.RateLimitError

    switch {
    case errors.As(err, &authErr):
        fmt.Println("Invalid API key")
    case errors.As(err, &bioErr):
        fmt.Println("Face not recognized or liveness failed")
    case errors.As(err, &rlErr):
        fmt.Printf("Rate limit — retry after %v\n", rlErr.RetryAfter)
    default:
        fmt.Println("Unexpected error:", err)
    }
}

Running Tests

go test ./...
go test ./... -v          # verbose
go test ./... -cover      # with coverage

Local Development

git clone <repo>
cd velix-sdk-go
go build ./...
go vet ./...
go test ./...

Get an API Key

Access the dashboard at velixbiometrics.com → Settings → API Keys → New Key.

Documentation

Overview

Package velix é o SDK oficial Go para a plataforma VELIX Biometrics.

Index

Constants

This section is empty.

Variables

View Source
var ErrTimeNotImplemented = errors.New("velix: Time (Velix Time) não está implementado — nenhum endpoint /v1/api/time/* existe hoje na API pública (ver task #593/#616)")

ErrTimeNotImplemented é retornado por todos os métodos de TimeModule.

Velix Time NÃO possui nenhum endpoint na superfície pública /v1/api/* (ver nota "COBERTURA PARCIAL" em lib-velix-contracts/openapi/public-api.yaml, task #593/#616). O GatewayModule de api-velix-identity-core só faz proxy BFF para edge, intelligence, copilot e marketplace — não existe proxy para api-velix-time hoje. Os escopos time:read/time:write estão reservados no ApiScope para quando essa lacuna for endereçada.

Functions

This section is empty.

Types

type AuthError

type AuthError struct{ VelixError }

AuthError credenciais inválidas ou expiradas.

type BiometricError

type BiometricError struct{ VelixError }

BiometricError falha de identificação ou enroll biométrico.

type CheckinIdentifyRequest

type CheckinIdentifyRequest struct {
	ImageBase64 string           `json:"imageBase64"`
	Images      []string         `json:"images,omitempty"`
	TopK        int              `json:"topK,omitempty"`
	Liveness    *LivenessBlock   `json:"liveness,omitempty"`
	Location    *CheckinLocation `json:"location,omitempty"`
}

CheckinIdentifyRequest contrato real de IdentifyFaceDto (src/modules/checkin/dto/identify-face.dto.ts).

type CheckinIdentifyResponse

type CheckinIdentifyResponse struct {
	Matched      bool    `json:"matched"`
	PersonID     *string `json:"person_id"`
	QualityScore float64 `json:"quality_score"`
	Message      string  `json:"message"`
}

CheckinIdentifyResponse resultado da identificação. Score de liveness NUNCA é exposto — apenas o booleano `matched`.

type CheckinLocation

type CheckinLocation struct {
	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
	Accuracy  float64 `json:"accuracy,omitempty"`
}

CheckinLocation geolocalização opcional do checkin.

type CheckinModule

type CheckinModule struct {
	// contains filtered or unexported fields
}

CheckinModule identificação biométrica via API key (Velix.ID).

func (*CheckinModule) Identify

Identify identifica uma pessoa por frame facial. Escopo exigido na API key: checkin:write. POST /v1/api/checkin/identify.

type Config

type Config struct {
	APIURL  string        // ex: "https://api.velixbiometrics.com"
	APIKey  string        // ex: "vx_live_..."
	JWT     string        // alternativa ao APIKey (Bearer token)
	Timeout time.Duration // default: 30s
}

Config opções de inicialização do VelixClient.

type CreateGuestRequest

type CreateGuestRequest struct {
	Name        string `json:"name"`
	Email       string `json:"email"`
	CPF         string `json:"cpf,omitempty"`
	Phone       string `json:"phone,omitempty"`
	BirthDate   string `json:"birthDate,omitempty"`
	CategoryID  string `json:"categoryId,omitempty"`
	CompanionOf string `json:"companionOf,omitempty"`
}

CreateGuestRequest contrato real de create-guest.dto.ts. Campos deste schema permanecem em camelCase no wire (birthDate, categoryId, companionOf), diferente do restante da superfície /v1/api/* que é snake_case.

type DeletionRequestBody

type DeletionRequestBody struct {
	PersonID string `json:"person_id"`
}

DeletionRequestBody corpo de POST /v1/api/deletion-request.

type DeletionRequestResponse

type DeletionRequestResponse struct {
	ProtocolNumber string `json:"protocol_number"`
	Message        string `json:"message"`
}

DeletionRequestResponse conteúdo de Envelope.data para POST /v1/api/deletion-request.

type EventsModule

type EventsModule struct {
	// contains filtered or unexported fields
}

EventsModule convidados de evento via API key (Velix Events). Cobertura MÍNIMA — apenas criar e consultar convidado, único mapeado na spec pública (task #593). Não expõe CRUD de eventos: não existe superfície de API key para isso hoje em api-velix-identity-core.

func (*EventsModule) CreateGuest

func (m *EventsModule) CreateGuest(ctx context.Context, eventID string, req CreateGuestRequest) (*GuestResponse, error)

CreateGuest cria um convidado de evento. Escopo exigido: events:write. POST /v1/api/events/{id}/guests.

func (*EventsModule) GetGuest

func (m *EventsModule) GetGuest(ctx context.Context, eventID, guestID string) (*GuestResponse, error)

GetGuest consulta um convidado de evento, incluindo status de checkin. Escopo exigido: events:read. GET /v1/api/events/{id}/guests/{guestId}.

type FrameResult

type FrameResult struct {
	FrameIndex     int     `json:"frame_index"`
	QualityPassed  bool    `json:"quality_passed"`
	QualityScore   float64 `json:"quality_score"`
	LivenessPassed bool    `json:"liveness_passed"`
}

FrameResult resultado de processamento de um frame individual de onboarding.

type GuestResponse

type GuestResponse struct {
	ID         string  `json:"id"`
	EventID    string  `json:"eventId"`
	Name       string  `json:"name"`
	Email      string  `json:"email"`
	Status     string  `json:"status"`
	CategoryID *string `json:"categoryId"`
}

GuestResponse EventGuest — retornado por POST .../guests e GET .../guests/{guestId}.

type LGPDModule

type LGPDModule struct {
	// contains filtered or unexported fields
}

LGPDModule solicitações de exclusão de dados via API key (Velix.ID).

func (*LGPDModule) DeletionRequest

func (m *LGPDModule) DeletionRequest(ctx context.Context, personID string) (*DeletionRequestResponse, error)

DeletionRequest solicita a exclusão dos dados de uma pessoa. A pessoa deve possuir uma Identity ativa vinculada ao tenant dono da API key, caso contrário a API retorna 403. Escopo exigido: lgpd:write. POST /v1/api/deletion-request.

type LivenessBlock

type LivenessBlock struct {
	Token   string           `json:"token"`
	Samples []LivenessSample `json:"samples"`
}

LivenessBlock bloco opcional de prova de vida ativa.

type LivenessSample

type LivenessSample struct {
	Action      string `json:"action"` // center, move_closer, move_away
	ImageBase64 string `json:"imageBase64"`
}

LivenessSample amostra de liveness ativo (contrato mantém camelCase no wire).

type MeModule

type MeModule struct {
	// contains filtered or unexported fields
}

MeModule consulta de dados de pessoa via API key (Velix.ID).

func (*MeModule) Get

func (m *MeModule) Get(ctx context.Context, personID string) (*MeResponse, error)

Get retorna os dados de uma pessoa pelo personId. Valida que a pessoa possui Identity vinculada ao tenant dono da API key, caso contrário a API retorna 403. Escopo exigido: me:read. GET /v1/api/me/{personId}.

type MeResponse

type MeResponse struct {
	ID        string  `json:"id"`
	Name      string  `json:"name"`
	Email     *string `json:"email"`
	Phone     *string `json:"phone"`
	PhotoURL  *string `json:"photo_url"`
	CreatedAt string  `json:"created_at"`
}

MeResponse conteúdo de Envelope.data para GET /v1/api/me/{personId}.

type NotFoundError

type NotFoundError struct{ VelixError }

NotFoundError recurso não encontrado.

type OnboardingModule

type OnboardingModule struct {
	// contains filtered or unexported fields
}

OnboardingModule cadastro biométrico via API key (Velix.ID).

func (*OnboardingModule) Create

Create realiza o onboarding biométrico de uma pessoa. Escopo exigido na API key: onboarding:write. POST /v1/api/onboarding.

type OnboardingRequest

type OnboardingRequest struct {
	Name         string         `json:"name"`
	Email        string         `json:"email,omitempty"`
	Phone        string         `json:"phone,omitempty"`
	Document     string         `json:"document,omitempty"`
	DocumentType string         `json:"document_type,omitempty"` // CPF, CNPJ, RG, PASSPORT, OTHER
	ExternalID   string         `json:"external_id,omitempty"`
	Metadata     map[string]any `json:"metadata,omitempty"`
	Frames       []string       `json:"frames"`         // JPEG base64, sem prefixo data URI, mínimo 1
	Role         string         `json:"role,omitempty"` // member, admin, tenant_admin
	AccessGroups []string       `json:"access_groups,omitempty"`
}

OnboardingRequest contrato real de OnboardingDto (src/modules/onboarding/dto/onboarding.dto.ts).

type OnboardingResponse

type OnboardingResponse struct {
	PersonID        string        `json:"person_id"`
	IdentityID      string        `json:"identity_id"`
	Enrolled        bool          `json:"enrolled"`
	FramesProcessed int           `json:"frames_processed"`
	FramesResults   []FrameResult `json:"frames_results"`
	EmbeddingID     *string       `json:"embedding_id"`
	Message         string        `json:"message"`
}

OnboardingResponse conteúdo de Envelope.data para POST /v1/api/onboarding.

type RateLimitError

type RateLimitError struct{ VelixError }

RateLimitError requisição bloqueada por rate limit.

type TimeModule

type TimeModule struct {
	// contains filtered or unexported fields
}

TimeModule placeholder para Velix Time. TODO(#616): implementar quando a API pública expuser endpoints de tempo/ponto — hoje não existem.

func (*TimeModule) PunchRecords

func (m *TimeModule) PunchRecords(ctx context.Context) error

PunchRecords é um stub — sempre retorna ErrTimeNotImplemented. TODO(#616): substituir por chamada real quando o endpoint existir.

type VelixClient

type VelixClient struct {
	Onboarding *OnboardingModule
	Checkin    *CheckinModule
	LGPD       *LGPDModule
	Me         *MeModule
	Events     *EventsModule
	Time       *TimeModule
	// contains filtered or unexported fields
}

VelixClient cliente principal do SDK. Cobre exclusivamente a superfície real /v1/api/* protegida por API key (task #593/#656) — Velix.ID (onboarding, checkin, LGPD, me) e cobertura mínima de Velix Events (guests). Velix Time não tem endpoints implementados hoje: ver TimeModule.

func NewClient

func NewClient(cfg Config) *VelixClient

NewClient cria um VelixClient configurado.

type VelixError

type VelixError struct {
	StatusCode int
	Message    string
	Code       string
}

VelixError erro base do SDK com código HTTP e mensagem da API.

func (*VelixError) Error

func (e *VelixError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL