notifica

package module
v0.0.0-...-f11faa6 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2026 License: MIT Imports: 9 Imported by: 0

README

notifica-go

Official Go SDK for the Notifica API.

Installation

go get github.com/notifica-tech/notifica-go

Requires Go 1.21+.

Quick Start

package main

import (
	"context"
	"fmt"
	"log"

	notifica "github.com/notifica-tech/notifica-go"
)

func main() {
	client := notifica.NewClient("nk_live_...")

	// Send an email notification
	n, err := client.Notifications.Send(context.Background(), &notifica.SendNotificationParams{
		Channel:    notifica.ChannelEmail,
		Recipient:  "user@example.com",
		TemplateID: "welcome-email",
		Payload:    map[string]any{"name": "Maria"},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Notification sent:", n.ID)
}

Usage

Client Configuration
// Default client
client := notifica.NewClient("nk_live_...")

// Custom base URL (for self-hosted or staging)
client := notifica.NewClient("nk_live_...", notifica.WithBaseURL("https://api.staging.notifica.com.br"))

// Custom HTTP client
client := notifica.NewClient("nk_live_...", notifica.WithHTTPClient(&http.Client{
    Timeout: 60 * time.Second,
}))
Notifications
// Send a notification with idempotency key
n, err := client.Notifications.Send(ctx, &notifica.SendNotificationParams{
    Channel:        notifica.ChannelSMS,
    Recipient:      "+5511999999999",
    Payload:        map[string]any{"code": "123456"},
    TemplateID:     "verification-code",
    IdempotencyKey: "unique-request-id",
})

// List notifications with filters
page, err := client.Notifications.List(ctx, &notifica.ListNotificationsParams{
    Status:  notifica.StatusDelivered,
    Channel: notifica.ChannelEmail,
    Limit:   50,
})

// Get a notification with delivery attempts
n, err := client.Notifications.Get(ctx, "notification-id")

// List delivery attempts
attempts, err := client.Notifications.ListAttempts(ctx, "notification-id")
Subscribers
// Create or upsert a subscriber
sub, err := client.Subscribers.Create(ctx, &notifica.CreateSubscriberParams{
    ExternalID: "user-123",
    Email:      "user@example.com",
    Name:       "Maria Silva",
    Phone:      "+5511999999999",
    CustomProperties: map[string]any{
        "plan": "pro",
    },
})

// List subscribers with search
page, err := client.Subscribers.List(ctx, &notifica.ListSubscribersParams{
    Search: "maria",
    Limit:  20,
})

// Update a subscriber
sub, err := client.Subscribers.Update(ctx, "subscriber-id", &notifica.UpdateSubscriberParams{
    Name: notifica.String("Maria Santos"),
})

// Delete a subscriber (LGPD-compliant soft delete)
err := client.Subscribers.Delete(ctx, "subscriber-id")

// Manage notification preferences
prefs, err := client.Subscribers.GetPreferences(ctx, "subscriber-id")

prefs, err = client.Subscribers.SetPreferences(ctx, "subscriber-id", &notifica.SetPreferencesParams{
    Preferences: []notifica.PreferenceInput{
        {Category: "marketing", Channel: "email", Enabled: false},
    },
})

// Bulk import subscribers
result, err := client.Subscribers.BulkImport(ctx, &notifica.BulkImportParams{
    Subscribers: []notifica.CreateSubscriberParams{
        {ExternalID: "user-1", Email: "a@example.com"},
        {ExternalID: "user-2", Email: "b@example.com"},
    },
})
Templates
// Create a template
tmpl, err := client.Templates.Create(ctx, &notifica.CreateTemplateParams{
    Channel: notifica.ChannelEmail,
    Slug:    "welcome",
    Name:    "Welcome Email",
    Content: "Hello {{name}}, welcome!",
    Status:  notifica.TemplateStatusPublished,
})

// List templates by channel
templates, err := client.Templates.List(ctx, &notifica.ListTemplatesParams{
    Channel: notifica.ChannelEmail,
})

// Preview a template with sample data
preview, err := client.Templates.Preview(ctx, "template-id", &notifica.PreviewParams{
    Variables: map[string]any{"name": "Maria"},
})

// Validate template syntax
result, err := client.Templates.Validate(ctx, "template-id")
Workflows
// Create a workflow
wf, err := client.Workflows.Create(ctx, &notifica.CreateWorkflowParams{
    Slug: "onboarding",
    Name: "Onboarding Flow",
    Steps: []map[string]any{
        {"type": "send", "channel": "email", "template": "welcome"},
        {"type": "delay", "duration": "24h"},
        {"type": "send", "channel": "email", "template": "getting-started"},
    },
})

// Trigger a workflow
run, err := client.Workflows.Trigger(ctx, "onboarding", &notifica.TriggerWorkflowParams{
    Recipient: "user-123",
    Data:      map[string]any{"name": "Maria"},
})

// Check workflow run status
run, err := client.Workflows.GetRun(ctx, "run-id")

// Cancel a running workflow
run, err := client.Workflows.CancelRun(ctx, "run-id")
Webhooks
// Create a webhook (secret is only returned here)
wh, err := client.Webhooks.Create(ctx, &notifica.CreateWebhookParams{
    URL:    "https://example.com/webhooks/notifica",
    Events: []string{"notification.sent", "notification.delivered", "notification.failed"},
})
fmt.Println("Signing secret:", wh.Secret)

// List webhook deliveries
deliveries, err := client.Webhooks.ListDeliveries(ctx, "webhook-id", &notifica.ListDeliveriesParams{
    Limit: 50,
})

// Send a test event
err := client.Webhooks.Test(ctx, "webhook-id")
Sending Domains
// Register a domain
domain, err := client.Domains.Create(ctx, &notifica.CreateDomainParams{
    Domain: "mail.example.com",
})

// Verify DNS records
domain, err = client.Domains.Verify(ctx, domain.ID)

// Check domain health
health, err := client.Domains.CheckHealth(ctx, domain.ID)
Analytics
// Get overview metrics
overview, err := client.Analytics.Overview(ctx, "7d")

// Get per-channel stats
stats, err := client.Analytics.ByChannel(ctx, "30d")

// Get timeseries data
ts, err := client.Analytics.Timeseries(ctx, &notifica.TimeseriesParams{
    Period:      "7d",
    Granularity: "day",
})

// Get top templates
top, err := client.Analytics.TopTemplates(ctx, &notifica.TopTemplatesParams{
    Period: "30d",
    Limit:  5,
})
In-App Notifications
// List in-app notifications for a subscriber
notifications, err := client.InApp.List(ctx, "subscriber-id", &notifica.ListInAppParams{
    UnreadOnly: true,
    Limit:      20,
})

// Mark as read
err := client.InApp.MarkRead(ctx, "subscriber-id", "notification-id")

// Mark all as read
err = client.InApp.MarkAllRead(ctx, "subscriber-id")

// Get unread count
count, err := client.InApp.GetUnreadCount(ctx, "subscriber-id")

Error Handling

n, err := client.Notifications.Send(ctx, params)
if err != nil {
    if notifica.IsValidationError(err) {
        // Handle 422: inspect err.(*notifica.Error).Details
    }
    if notifica.IsRateLimited(err) {
        // Handle 429: back off and retry
    }
    if notifica.IsNotFound(err) {
        // Handle 404
    }

    // Access full error details
    var apiErr *notifica.Error
    if errors.As(err, &apiErr) {
        fmt.Println(apiErr.Code, apiErr.Message, apiErr.Details)
    }
}

Helpers

// String returns a pointer to a string (useful for optional fields)
name := notifica.String("Maria")

// Bool returns a pointer to a bool
active := notifica.Bool(true)

License

MIT

Documentation

Overview

Package notifica provides a Go client for the Notifica API.

Usage:

client := notifica.NewClient("nk_live_...")

// Send a notification
n, err := client.Notifications.Send(ctx, &notifica.SendNotificationParams{
    Channel:   notifica.ChannelEmail,
    Recipient: "user@example.com",
    Payload:   map[string]any{"name": "John"},
})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool

func Bool(b bool) *bool

Bool returns a pointer to the given bool.

func Int

func Int(i int) *int

Int returns a pointer to the given int.

func IsConflict

func IsConflict(err error) bool

IsConflict returns true if the error is a 409.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound returns true if the error is a 404.

func IsRateLimited

func IsRateLimited(err error) bool

IsRateLimited returns true if the error is a 429.

func IsValidationError

func IsValidationError(err error) bool

IsValidationError returns true if the error is a 422.

func String

func String(s string) *string

String returns a pointer to the given string.

Types

type APIKey

type APIKey struct {
	ID          string     `json:"id"`
	KeyPrefix   string     `json:"key_prefix"`
	KeyType     string     `json:"key_type"`    // "secret" or "public"
	Environment string     `json:"environment"` // "production" or "sandbox"
	Label       string     `json:"label"`
	Key         string     `json:"key,omitempty"` // Only returned on creation
	LastUsedAt  *Timestamp `json:"last_used_at,omitempty"`
	RevokedAt   *Timestamp `json:"revoked_at,omitempty"`
	CreatedAt   Timestamp  `json:"created_at"`
}

APIKey represents an API key.

type APIKeyService

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

APIKeyService handles API key operations.

func (*APIKeyService) Create

func (s *APIKeyService) Create(ctx context.Context, params *CreateAPIKeyParams) (*APIKey, error)

Create creates a new API key. The raw key is only returned on creation.

func (*APIKeyService) List

func (s *APIKeyService) List(ctx context.Context) ([]APIKey, error)

List lists all non-revoked API keys.

func (*APIKeyService) Revoke

func (s *APIKeyService) Revoke(ctx context.Context, id string) error

Revoke revokes an API key.

type AnalyticsOverview

type AnalyticsOverview struct {
	Sent      int `json:"sent"`
	Delivered int `json:"delivered"`
	Failed    int `json:"failed"`
}

AnalyticsOverview represents summary metrics.

type AnalyticsService

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

AnalyticsService handles analytics operations.

func (*AnalyticsService) ByChannel

func (s *AnalyticsService) ByChannel(ctx context.Context, period string) ([]ChannelStats, error)

ByChannel returns per-channel statistics.

func (*AnalyticsService) Overview

func (s *AnalyticsService) Overview(ctx context.Context, period string) (*AnalyticsOverview, error)

Overview returns summary metrics for a period. Period can be "1h", "24h", "7d", or "30d" (default: "24h").

func (*AnalyticsService) Timeseries

func (s *AnalyticsService) Timeseries(ctx context.Context, params *TimeseriesParams) ([]TimeseriesPoint, error)

Timeseries returns time-bucketed analytics data.

func (*AnalyticsService) TopTemplates

func (s *AnalyticsService) TopTemplates(ctx context.Context, params *TopTemplatesParams) ([]TemplateStats, error)

TopTemplates returns the most-used templates.

type BulkImportParams

type BulkImportParams struct {
	Subscribers []CreateSubscriberParams `json:"subscribers"`
}

BulkImportParams are the parameters for bulk importing subscribers.

type BulkImportResult

type BulkImportResult struct {
	Imported    int          `json:"imported"`
	Subscribers []Subscriber `json:"subscribers"`
}

BulkImportResult is the result of a bulk import.

type Channel

type Channel string

Channel represents a notification delivery channel.

const (
	ChannelEmail    Channel = "email"
	ChannelSMS      Channel = "sms"
	ChannelWhatsApp Channel = "whatsapp"
	ChannelInApp    Channel = "in_app"
	ChannelPush     Channel = "push"
)

type ChannelConfiguration

type ChannelConfiguration struct {
	ID             string         `json:"id"`
	Channel        Channel        `json:"channel"`
	Provider       string         `json:"provider"`
	Settings       map[string]any `json:"settings,omitempty"`
	HasCredentials bool           `json:"has_credentials"`
	VerifiedAt     *Timestamp     `json:"verified_at,omitempty"`
	Active         bool           `json:"active"`
	InsertedAt     Timestamp      `json:"inserted_at"`
	UpdatedAt      Timestamp      `json:"updated_at"`
}

ChannelConfiguration represents a configured delivery channel.

type ChannelService

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

ChannelService handles channel configuration operations.

func (*ChannelService) Create

Create creates a channel configuration.

func (*ChannelService) Delete

func (s *ChannelService) Delete(ctx context.Context, channel Channel) error

Delete deletes a channel configuration.

func (*ChannelService) Get

Get retrieves a specific channel configuration.

func (*ChannelService) List

List lists all channel configurations.

func (*ChannelService) Test

func (s *ChannelService) Test(ctx context.Context, channel Channel) (*TestResult, error)

Test sends a test notification through a channel.

func (*ChannelService) Update

Update updates a channel configuration.

type ChannelStats

type ChannelStats struct {
	Channel   string `json:"channel"`
	Sent      int    `json:"sent"`
	Delivered int    `json:"delivered"`
	Failed    int    `json:"failed"`
}

ChannelStats represents per-channel statistics.

type Client

type Client struct {
	Notifications *NotificationService
	Subscribers   *SubscriberService
	Templates     *TemplateService
	Channels      *ChannelService
	Workflows     *WorkflowService
	Webhooks      *WebhookService
	Analytics     *AnalyticsService
	APIKeys       *APIKeyService
	Domains       *DomainService
	InApp         *InAppService
	// contains filtered or unexported fields
}

Client is the Notifica API client.

func NewClient

func NewClient(apiKey string, opts ...Option) *Client

NewClient creates a new Notifica API client.

type Consent struct {
	GivenAt   *Timestamp `json:"given_at,omitempty"`
	Method    string     `json:"method,omitempty"`
	IP        string     `json:"ip,omitempty"`
	RevokedAt *Timestamp `json:"revoked_at,omitempty"`
}

Consent tracks LGPD consent information.

type CreateAPIKeyParams

type CreateAPIKeyParams struct {
	KeyType     string `json:"key_type"` // "secret" or "public"
	Label       string `json:"label"`
	Environment string `json:"environment"` // "sandbox" or "production"
}

CreateAPIKeyParams are the parameters for creating an API key.

type CreateChannelParams

type CreateChannelParams struct {
	Channel     Channel        `json:"channel"`
	Provider    string         `json:"provider"`
	Credentials map[string]any `json:"credentials,omitempty"`
	Settings    map[string]any `json:"settings,omitempty"`
	Active      *bool          `json:"active,omitempty"`
}

CreateChannelParams are the parameters for creating a channel configuration.

type CreateDomainParams

type CreateDomainParams struct {
	Domain string `json:"domain"`
}

CreateDomainParams are the parameters for registering a domain.

type CreateSubscriberParams

type CreateSubscriberParams struct {
	ExternalID       string         `json:"external_id"`
	Email            string         `json:"email,omitempty"`
	Phone            string         `json:"phone,omitempty"`
	Name             string         `json:"name,omitempty"`
	Locale           string         `json:"locale,omitempty"`
	Timezone         string         `json:"timezone,omitempty"`
	CustomProperties map[string]any `json:"custom_properties,omitempty"`
}

CreateSubscriberParams are the parameters for creating or upserting a subscriber.

type CreateTemplateParams

type CreateTemplateParams struct {
	Channel   Channel        `json:"channel"`
	Slug      string         `json:"slug"`
	Name      string         `json:"name,omitempty"`
	Content   string         `json:"content"`
	Variables []string       `json:"variables,omitempty"`
	Variants  map[string]any `json:"variants,omitempty"`
	Language  string         `json:"language,omitempty"`
	Status    TemplateStatus `json:"status,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

CreateTemplateParams are the parameters for creating a template.

type CreateWebhookParams

type CreateWebhookParams struct {
	URL    string   `json:"url"`
	Events []string `json:"events"`
	Active *bool    `json:"active,omitempty"`
}

CreateWebhookParams are the parameters for creating a webhook.

type CreateWorkflowParams

type CreateWorkflowParams struct {
	Slug   string           `json:"slug"`
	Name   string           `json:"name"`
	Steps  []map[string]any `json:"steps"`
	Active *bool            `json:"active,omitempty"`
}

CreateWorkflowParams are the parameters for creating a workflow.

type CursorMeta

type CursorMeta struct {
	Cursor     *string `json:"cursor"`
	HasMore    bool    `json:"has_more"`
	TotalCount *int    `json:"total_count,omitempty"`
}

CursorMeta contains cursor pagination metadata.

type CursorPage

type CursorPage[T any] struct {
	Data []T        `json:"data"`
	Meta CursorMeta `json:"meta"`
}

CursorPage represents a cursor-paginated response.

type DNSRecords

type DNSRecords struct {
	TXT           string `json:"txt,omitempty"`
	DKIMVerified  bool   `json:"dkim_verified"`
	SPFVerified   bool   `json:"spf_verified"`
	DMARCVerified bool   `json:"dmarc_verified"`
}

DNSRecords contains the DNS verification records for a domain.

type Domain

type Domain struct {
	ID                string       `json:"id"`
	Domain            string       `json:"domain"`
	Status            DomainStatus `json:"status"`
	VerificationToken string       `json:"verification_token,omitempty"`
	DNSRecords        *DNSRecords  `json:"dns_records,omitempty"`
	DKIMSelector      string       `json:"dkim_selector,omitempty"`
	DKIMConfigured    bool         `json:"dkim_configured"`
	DKIMVerified      bool         `json:"dkim_verified"`
	DKIMPublicKey     string       `json:"dkim_public_key,omitempty"`
	VerifiedAt        *Timestamp   `json:"verified_at,omitempty"`
	InsertedAt        Timestamp    `json:"inserted_at"`
	UpdatedAt         Timestamp    `json:"updated_at"`
}

Domain represents a sending domain.

type DomainAlert

type DomainAlert struct {
	DomainID string `json:"domain_id"`
	Domain   string `json:"domain"`
	Type     string `json:"type"`
	Message  string `json:"message"`
}

DomainAlert represents a domain health alert.

type DomainHealth

type DomainHealth struct {
	SPF   HealthCheck `json:"spf"`
	DKIM  HealthCheck `json:"dkim"`
	DMARC HealthCheck `json:"dmarc"`
}

DomainHealth represents the health status of a domain.

type DomainService

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

DomainService handles sending domain operations.

func (*DomainService) CheckHealth

func (s *DomainService) CheckHealth(ctx context.Context, domainID string) (*DomainHealth, error)

CheckHealth runs a health check on a domain.

func (*DomainService) Create

func (s *DomainService) Create(ctx context.Context, params *CreateDomainParams) (*Domain, error)

Create registers a new sending domain for verification.

func (*DomainService) Delete

func (s *DomainService) Delete(ctx context.Context, id string) error

Delete deletes a sending domain.

func (*DomainService) Get

func (s *DomainService) Get(ctx context.Context, id string) (*Domain, error)

Get retrieves a domain with its DNS records.

func (*DomainService) GetHealth

func (s *DomainService) GetHealth(ctx context.Context, domainID string) (*DomainHealth, error)

GetHealth returns the health status of a domain.

func (*DomainService) List

func (s *DomainService) List(ctx context.Context) ([]Domain, error)

List lists all sending domains.

func (*DomainService) ListAlerts

func (s *DomainService) ListAlerts(ctx context.Context) ([]DomainAlert, error)

ListAlerts returns domain health alerts.

func (*DomainService) Verify

func (s *DomainService) Verify(ctx context.Context, id string) (*Domain, error)

Verify triggers DNS verification for a domain.

type DomainStatus

type DomainStatus string

DomainStatus represents the verification status of a sending domain.

const (
	DomainStatusPending  DomainStatus = "pending"
	DomainStatusVerified DomainStatus = "verified"
)

type Error

type Error struct {
	StatusCode int                 `json:"-"`
	Code       string              `json:"code"`
	Message    string              `json:"message"`
	DocURL     string              `json:"doc_url,omitempty"`
	Details    map[string][]string `json:"details,omitempty"`
}

Error represents an API error returned by Notifica.

func (*Error) Error

func (e *Error) Error() string

type HealthCheck

type HealthCheck struct {
	Status  string `json:"status"`
	Details string `json:"details,omitempty"`
}

HealthCheck represents a single DNS health check.

type InAppNotification

type InAppNotification struct {
	ID        string         `json:"id"`
	Title     string         `json:"title,omitempty"`
	Body      string         `json:"body,omitempty"`
	Data      map[string]any `json:"data,omitempty"`
	ReadAt    *Timestamp     `json:"read_at,omitempty"`
	CreatedAt Timestamp      `json:"created_at"`
}

InAppNotification represents an in-app notification for a subscriber.

type InAppService

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

InAppService handles in-app notification operations.

func (*InAppService) GetUnreadCount

func (s *InAppService) GetUnreadCount(ctx context.Context, subscriberID string) (int, error)

GetUnreadCount returns the unread notification count for a subscriber.

func (*InAppService) List

func (s *InAppService) List(ctx context.Context, subscriberID string, params *ListInAppParams) ([]InAppNotification, error)

List lists in-app notifications for a subscriber.

func (*InAppService) MarkAllRead

func (s *InAppService) MarkAllRead(ctx context.Context, subscriberID string) error

MarkAllRead marks all in-app notifications as read for a subscriber.

func (*InAppService) MarkRead

func (s *InAppService) MarkRead(ctx context.Context, subscriberID, notificationID string) error

MarkRead marks a single in-app notification as read.

type ListDeliveriesParams

type ListDeliveriesParams struct {
	Limit int `json:"limit,omitempty"`
}

ListDeliveriesParams are the optional filters for listing webhook deliveries.

type ListInAppParams

type ListInAppParams struct {
	Limit      int  `json:"limit,omitempty"`
	Offset     int  `json:"offset,omitempty"`
	UnreadOnly bool `json:"unread_only,omitempty"`
}

ListInAppParams are the optional filters for listing in-app notifications.

type ListNotificationsParams

type ListNotificationsParams struct {
	Limit   int                `json:"limit,omitempty"`
	Cursor  string             `json:"cursor,omitempty"`
	Status  NotificationStatus `json:"status,omitempty"`
	Channel Channel            `json:"channel,omitempty"`
}

ListNotificationsParams are the optional filters for listing notifications.

type ListRunsParams

type ListRunsParams struct {
	Status     string `json:"status,omitempty"`
	WorkflowID string `json:"workflow_id,omitempty"`
	Limit      int    `json:"limit,omitempty"`
}

ListRunsParams are the optional filters for listing workflow runs.

type ListSubscribersParams

type ListSubscribersParams struct {
	Limit  int    `json:"limit,omitempty"`
	Offset int    `json:"offset,omitempty"`
	Search string `json:"search,omitempty"`
}

ListSubscribersParams are the optional filters for listing subscribers.

type ListTemplatesParams

type ListTemplatesParams struct {
	Channel Channel        `json:"channel,omitempty"`
	Status  TemplateStatus `json:"status,omitempty"`
}

ListTemplatesParams are the optional filters for listing templates.

type MessageAttempt

type MessageAttempt struct {
	ID               string     `json:"id"`
	Channel          string     `json:"channel"`
	Provider         string     `json:"provider"`
	Status           string     `json:"status"`
	ProviderResponse any        `json:"provider_response,omitempty"`
	AttemptNumber    int        `json:"attempt_number"`
	Error            *string    `json:"error,omitempty"`
	StartedAt        *Timestamp `json:"started_at,omitempty"`
	CompletedAt      *Timestamp `json:"completed_at,omitempty"`
}

MessageAttempt represents a delivery attempt for a notification.

type Notification

type Notification struct {
	ID             string             `json:"id"`
	Channel        Channel            `json:"channel"`
	TemplateID     *string            `json:"template_id,omitempty"`
	Recipient      string             `json:"recipient"`
	Payload        map[string]any     `json:"payload,omitempty"`
	Status         NotificationStatus `json:"status"`
	Metadata       map[string]any     `json:"metadata,omitempty"`
	IdempotencyKey *string            `json:"idempotency_key,omitempty"`
	AcceptedAt     *Timestamp         `json:"accepted_at,omitempty"`
	SentAt         *Timestamp         `json:"sent_at,omitempty"`
	DeliveredAt    *Timestamp         `json:"delivered_at,omitempty"`
	InsertedAt     Timestamp          `json:"inserted_at"`
	UpdatedAt      Timestamp          `json:"updated_at"`
	Attempts       []MessageAttempt   `json:"attempts,omitempty"`
}

Notification represents a notification object.

type NotificationService

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

NotificationService handles notification operations.

func (*NotificationService) Get

Get retrieves a notification by ID, including its delivery attempts.

func (*NotificationService) List

List lists notifications with cursor-based pagination.

func (*NotificationService) ListAttempts

func (s *NotificationService) ListAttempts(ctx context.Context, notificationID string) ([]MessageAttempt, error)

ListAttempts lists the delivery attempts for a notification.

func (*NotificationService) Send

Send sends a notification. Returns the notification with a 202 Accepted status.

type NotificationStatus

type NotificationStatus string

NotificationStatus represents the delivery status of a notification.

const (
	StatusPending   NotificationStatus = "pending"
	StatusAccepted  NotificationStatus = "accepted"
	StatusSent      NotificationStatus = "sent"
	StatusDelivered NotificationStatus = "delivered"
	StatusFailed    NotificationStatus = "failed"
)

type OffsetPage

type OffsetPage[T any] struct {
	Data  []T `json:"data"`
	Total int `json:"total"`
}

OffsetPage represents an offset-paginated response.

type Option

type Option func(*Client)

Option configures the Client.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL overrides the default API base URL.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sets a custom HTTP client.

type PreferenceInput

type PreferenceInput struct {
	Category string `json:"category"`
	Channel  string `json:"channel"`
	Enabled  bool   `json:"enabled"`
}

PreferenceInput is a single preference entry.

type PreviewContentParams

type PreviewContentParams struct {
	Content   string         `json:"content"`
	Channel   Channel        `json:"channel"`
	Variables map[string]any `json:"variables,omitempty"`
	Variants  map[string]any `json:"variants,omitempty"`
}

PreviewContentParams are the parameters for previewing unsaved template content.

type PreviewParams

type PreviewParams struct {
	Variables map[string]any `json:"variables,omitempty"`
}

PreviewParams are the parameters for previewing a template.

type PreviewResult

type PreviewResult struct {
	Output    string   `json:"output,omitempty"`
	Variables []string `json:"variables,omitempty"`
	Valid     bool     `json:"valid"`
	Errors    []string `json:"errors,omitempty"`
	Warnings  []string `json:"warnings,omitempty"`
}

PreviewResult is the result of a template preview or validation.

type SendNotificationParams

type SendNotificationParams struct {
	Channel        Channel        `json:"channel"`
	Recipient      string         `json:"recipient"`
	TemplateID     string         `json:"template_id,omitempty"`
	Payload        map[string]any `json:"payload,omitempty"`
	Metadata       map[string]any `json:"metadata,omitempty"`
	IdempotencyKey string         `json:"-"`
}

SendNotificationParams are the parameters for sending a notification.

type SetPreferencesParams

type SetPreferencesParams struct {
	Preferences []PreferenceInput `json:"preferences"`
}

SetPreferencesParams are the parameters for setting subscriber preferences.

type Subscriber

type Subscriber struct {
	ID               string         `json:"id"`
	ExternalID       string         `json:"external_id"`
	Email            *string        `json:"email,omitempty"`
	Phone            *string        `json:"phone,omitempty"`
	Name             *string        `json:"name,omitempty"`
	Locale           *string        `json:"locale,omitempty"`
	Timezone         *string        `json:"timezone,omitempty"`
	CustomProperties map[string]any `json:"custom_properties,omitempty"`
	Consent          *Consent       `json:"consent,omitempty"`
	InsertedAt       Timestamp      `json:"inserted_at"`
	UpdatedAt        Timestamp      `json:"updated_at"`
}

Subscriber represents a subscriber.

type SubscriberPreference

type SubscriberPreference struct {
	ID         string     `json:"id"`
	Category   string     `json:"category"`
	Channel    string     `json:"channel"`
	Enabled    bool       `json:"enabled"`
	OptedOutAt *Timestamp `json:"opted_out_at,omitempty"`
}

SubscriberPreference represents a notification preference.

type SubscriberService

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

SubscriberService handles subscriber operations.

func (*SubscriberService) BulkImport

func (s *SubscriberService) BulkImport(ctx context.Context, params *BulkImportParams) (*BulkImportResult, error)

BulkImport imports multiple subscribers in a single transaction.

func (*SubscriberService) Create

Create creates or upserts a subscriber by external_id.

func (*SubscriberService) Delete

func (s *SubscriberService) Delete(ctx context.Context, id string) error

Delete soft-deletes a subscriber (LGPD-compliant PII nullification).

func (*SubscriberService) Get

Get retrieves a subscriber by ID.

func (*SubscriberService) GetPreferences

func (s *SubscriberService) GetPreferences(ctx context.Context, subscriberID string) ([]SubscriberPreference, error)

GetPreferences retrieves notification preferences for a subscriber.

func (*SubscriberService) List

List lists subscribers with offset-based pagination.

func (*SubscriberService) SetPreferences

func (s *SubscriberService) SetPreferences(ctx context.Context, subscriberID string, params *SetPreferencesParams) ([]SubscriberPreference, error)

SetPreferences sets notification preferences for a subscriber.

func (*SubscriberService) Update

Update updates a subscriber.

type Template

type Template struct {
	ID                 string         `json:"id"`
	Channel            Channel        `json:"channel"`
	Slug               string         `json:"slug"`
	Name               *string        `json:"name,omitempty"`
	Language           *string        `json:"language,omitempty"`
	Content            string         `json:"content"`
	Variables          []string       `json:"variables,omitempty"`
	Variants           map[string]any `json:"variants,omitempty"`
	Metadata           map[string]any `json:"metadata,omitempty"`
	Status             TemplateStatus `json:"status"`
	ProviderTemplateID *string        `json:"provider_template_id,omitempty"`
	InsertedAt         Timestamp      `json:"inserted_at"`
	UpdatedAt          Timestamp      `json:"updated_at"`
}

Template represents a notification template.

type TemplateService

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

TemplateService handles template operations.

func (*TemplateService) Create

func (s *TemplateService) Create(ctx context.Context, params *CreateTemplateParams) (*Template, error)

Create creates a new template.

func (*TemplateService) Delete

func (s *TemplateService) Delete(ctx context.Context, id string) error

Delete deletes a template.

func (*TemplateService) Get

func (s *TemplateService) Get(ctx context.Context, id string) (*Template, error)

Get retrieves a template by ID.

func (*TemplateService) List

func (s *TemplateService) List(ctx context.Context, params *ListTemplatesParams) ([]Template, error)

List lists all templates.

func (*TemplateService) Preview

func (s *TemplateService) Preview(ctx context.Context, id string, params *PreviewParams) (*PreviewResult, error)

Preview renders a saved template with sample data.

func (*TemplateService) PreviewContent

func (s *TemplateService) PreviewContent(ctx context.Context, params *PreviewContentParams) (*PreviewResult, error)

PreviewContent renders unsaved template content with sample data.

func (*TemplateService) Update

func (s *TemplateService) Update(ctx context.Context, id string, params *UpdateTemplateParams) (*Template, error)

Update updates a template.

func (*TemplateService) Validate

func (s *TemplateService) Validate(ctx context.Context, id string) (*PreviewResult, error)

Validate validates a saved template.

func (*TemplateService) ValidateContent

func (s *TemplateService) ValidateContent(ctx context.Context, params *ValidateContentParams) (*PreviewResult, error)

ValidateContent validates unsaved template content.

type TemplateStats

type TemplateStats struct {
	TemplateID string `json:"template_id"`
	Name       string `json:"name"`
	Slug       string `json:"slug"`
	Channel    string `json:"channel"`
	Count      int    `json:"count"`
}

TemplateStats represents usage statistics for a template.

type TemplateStatus

type TemplateStatus string

TemplateStatus represents the status of a template.

const (
	TemplateStatusDraft     TemplateStatus = "draft"
	TemplateStatusPublished TemplateStatus = "published"
)

type TestResult

type TestResult struct {
	Message string `json:"message"`
}

TestResult is the result of a channel test.

type TimeseriesParams

type TimeseriesParams struct {
	Period      string // "1h", "24h", "7d", "30d"
	Granularity string // "hour" or "day"
}

TimeseriesParams are the optional parameters for the timeseries endpoint.

type TimeseriesPoint

type TimeseriesPoint struct {
	Timestamp string `json:"timestamp"`
	Sent      int    `json:"sent"`
	Delivered int    `json:"delivered"`
	Failed    int    `json:"failed"`
}

TimeseriesPoint represents a single data point in a timeseries.

type Timestamp

type Timestamp struct {
	time.Time
}

Timestamp is a time.Time that unmarshals from ISO 8601 JSON strings.

func (*Timestamp) UnmarshalJSON

func (t *Timestamp) UnmarshalJSON(data []byte) error

type TopTemplatesParams

type TopTemplatesParams struct {
	Period string
	Limit  int
}

TopTemplatesParams are the optional parameters for the top templates endpoint.

type TriggerWorkflowParams

type TriggerWorkflowParams struct {
	Recipient      string         `json:"recipient"`
	Data           map[string]any `json:"data,omitempty"`
	IdempotencyKey string         `json:"-"`
}

TriggerWorkflowParams are the parameters for triggering a workflow.

type UnreadCount

type UnreadCount struct {
	Count int `json:"count"`
}

UnreadCount represents the unread notification count.

type UpdateChannelParams

type UpdateChannelParams struct {
	Provider    *string        `json:"provider,omitempty"`
	Credentials map[string]any `json:"credentials,omitempty"`
	Settings    map[string]any `json:"settings,omitempty"`
	Active      *bool          `json:"active,omitempty"`
}

UpdateChannelParams are the parameters for updating a channel configuration.

type UpdateSubscriberParams

type UpdateSubscriberParams struct {
	Email            *string        `json:"email,omitempty"`
	Phone            *string        `json:"phone,omitempty"`
	Name             *string        `json:"name,omitempty"`
	Locale           *string        `json:"locale,omitempty"`
	Timezone         *string        `json:"timezone,omitempty"`
	CustomProperties map[string]any `json:"custom_properties,omitempty"`
}

UpdateSubscriberParams are the parameters for updating a subscriber.

type UpdateTemplateParams

type UpdateTemplateParams struct {
	Name      *string        `json:"name,omitempty"`
	Content   *string        `json:"content,omitempty"`
	Variables []string       `json:"variables,omitempty"`
	Variants  map[string]any `json:"variants,omitempty"`
	Language  *string        `json:"language,omitempty"`
	Status    TemplateStatus `json:"status,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

UpdateTemplateParams are the parameters for updating a template.

type UpdateWebhookParams

type UpdateWebhookParams struct {
	URL    *string  `json:"url,omitempty"`
	Events []string `json:"events,omitempty"`
	Active *bool    `json:"active,omitempty"`
}

UpdateWebhookParams are the parameters for updating a webhook.

type UpdateWorkflowParams

type UpdateWorkflowParams struct {
	Name   *string          `json:"name,omitempty"`
	Steps  []map[string]any `json:"steps,omitempty"`
	Active *bool            `json:"active,omitempty"`
}

UpdateWorkflowParams are the parameters for updating a workflow.

type ValidateContentParams

type ValidateContentParams struct {
	Content  string         `json:"content"`
	Channel  Channel        `json:"channel"`
	Variants map[string]any `json:"variants,omitempty"`
}

ValidateContentParams are the parameters for validating unsaved template content.

type Webhook

type Webhook struct {
	ID         string    `json:"id"`
	URL        string    `json:"url"`
	Events     []string  `json:"events"`
	Secret     string    `json:"secret,omitempty"`
	Active     bool      `json:"active"`
	InsertedAt Timestamp `json:"inserted_at"`
	UpdatedAt  Timestamp `json:"updated_at"`
}

Webhook represents an outbound webhook.

type WebhookDelivery

type WebhookDelivery struct {
	ID             string     `json:"id"`
	EventType      string     `json:"event_type"`
	Attempts       int        `json:"attempts"`
	ResponseStatus *int       `json:"response_status,omitempty"`
	DeliveredAt    *Timestamp `json:"delivered_at,omitempty"`
	FailedAt       *Timestamp `json:"failed_at,omitempty"`
	NextRetryAt    *Timestamp `json:"next_retry_at,omitempty"`
	CreatedAt      Timestamp  `json:"created_at"`
}

WebhookDelivery represents a webhook delivery attempt.

type WebhookService

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

WebhookService handles outbound webhook operations.

func (*WebhookService) Create

func (s *WebhookService) Create(ctx context.Context, params *CreateWebhookParams) (*Webhook, error)

Create creates a webhook. The signing secret is only returned on creation.

func (*WebhookService) Delete

func (s *WebhookService) Delete(ctx context.Context, id string) error

Delete deletes a webhook.

func (*WebhookService) Get

func (s *WebhookService) Get(ctx context.Context, id string) (*Webhook, error)

Get retrieves a webhook by ID. The secret will be masked.

func (*WebhookService) List

func (s *WebhookService) List(ctx context.Context) ([]Webhook, error)

List lists all webhooks.

func (*WebhookService) ListDeliveries

func (s *WebhookService) ListDeliveries(ctx context.Context, webhookID string, params *ListDeliveriesParams) (*CursorPage[WebhookDelivery], error)

ListDeliveries lists delivery attempts for a webhook.

func (*WebhookService) Test

func (s *WebhookService) Test(ctx context.Context, id string) error

Test sends a test event to a webhook.

func (*WebhookService) Update

func (s *WebhookService) Update(ctx context.Context, id string, params *UpdateWebhookParams) (*Webhook, error)

Update updates a webhook.

type Workflow

type Workflow struct {
	ID         string           `json:"id"`
	Slug       string           `json:"slug"`
	Name       string           `json:"name"`
	Steps      []map[string]any `json:"steps"`
	Version    int              `json:"version"`
	Active     bool             `json:"active"`
	InsertedAt Timestamp        `json:"inserted_at"`
	UpdatedAt  Timestamp        `json:"updated_at"`
}

Workflow represents a notification workflow.

type WorkflowRun

type WorkflowRun struct {
	ID          string           `json:"id"`
	WorkflowID  string           `json:"workflow_id"`
	Status      string           `json:"status"`
	StepResults []map[string]any `json:"step_results,omitempty"`
	InsertedAt  Timestamp        `json:"inserted_at"`
	UpdatedAt   Timestamp        `json:"updated_at"`
}

WorkflowRun represents a single execution of a workflow.

type WorkflowService

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

WorkflowService handles workflow operations.

func (*WorkflowService) CancelRun

func (s *WorkflowService) CancelRun(ctx context.Context, id string) (*WorkflowRun, error)

CancelRun cancels a running workflow. Returns an error if the run is not in a running state.

func (*WorkflowService) Create

func (s *WorkflowService) Create(ctx context.Context, params *CreateWorkflowParams) (*Workflow, error)

Create creates a new workflow.

func (*WorkflowService) Delete

func (s *WorkflowService) Delete(ctx context.Context, id string) error

Delete soft-deletes a workflow.

func (*WorkflowService) Get

func (s *WorkflowService) Get(ctx context.Context, id string) (*Workflow, error)

Get retrieves a workflow by ID.

func (*WorkflowService) GetRun

func (s *WorkflowService) GetRun(ctx context.Context, id string) (*WorkflowRun, error)

GetRun retrieves a workflow run by ID with step results.

func (*WorkflowService) List

func (s *WorkflowService) List(ctx context.Context) ([]Workflow, error)

List lists all workflows.

func (*WorkflowService) ListRuns

func (s *WorkflowService) ListRuns(ctx context.Context, params *ListRunsParams) ([]WorkflowRun, error)

ListRuns lists workflow runs.

func (*WorkflowService) Trigger

func (s *WorkflowService) Trigger(ctx context.Context, slug string, params *TriggerWorkflowParams) (*WorkflowRun, error)

Trigger triggers a workflow run by slug.

func (*WorkflowService) Update

func (s *WorkflowService) Update(ctx context.Context, id string, params *UpdateWorkflowParams) (*Workflow, error)

Update updates a workflow. Bumps the version.

Jump to

Keyboard shortcuts

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