synapse

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 2, 2026 License: MIT Imports: 15 Imported by: 0

README

PYRX Synapse Go SDK

Official Go SDK for the PYRX Synapse customer engagement platform.

Installation

go get github.com/pyrx-tech/pyrx-synapse-go

Quick Start

package main

import (
	"fmt"
	"log"

	synapse "github.com/pyrx-tech/pyrx-synapse-go"
)

func main() {
	client, err := synapse.NewClient(synapse.Config{
		APIKey:      "psk_live_your_api_key",
		WorkspaceID: "your_workspace_id",
	})
	if err != nil {
		log.Fatal(err)
	}

	// Track an event
	resp, err := client.Track(synapse.TrackParams{
		ExternalID: "user_123",
		EventName:  "purchase_completed",
		Attributes: map[string]interface{}{
			"amount":   99.99,
			"currency": "USD",
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Event tracked: %s\n", resp.EventID)
}

Usage

Configuration
client, err := synapse.NewClient(synapse.Config{
	APIKey:      "psk_live_your_api_key",  // Required
	WorkspaceID: "your_workspace_id",       // Required
	BaseURL:     "https://synapse-api.pyrx.tech", // Optional (default)
	Timeout:     30 * time.Second,          // Optional (default: 30s)
	MaxRetries:  3,                         // Optional (default: 3)
})
Track Events
// Single event
resp, err := client.Track(synapse.TrackParams{
	ExternalID: "user_123",
	EventName:  "page_viewed",
	Attributes: map[string]interface{}{
		"page": "/pricing",
	},
})

// Batch events
batchResp, err := client.TrackBatch(synapse.TrackBatchParams{
	Events: []synapse.TrackParams{
		{ExternalID: "user_1", EventName: "click"},
		{ExternalID: "user_2", EventName: "view"},
	},
})
Identify Contacts
// Single contact
contact, err := client.Identify(synapse.IdentifyParams{
	ExternalID: "user_123",
	Email:      "jane@example.com",
	FirstName:  "Jane",
	LastName:   "Doe",
	Properties: map[string]interface{}{
		"plan": "pro",
	},
})

// Batch contacts
bulkResp, err := client.IdentifyBatch(synapse.IdentifyBatchParams{
	Contacts: []synapse.IdentifyParams{
		{ExternalID: "user_1", Email: "a@example.com"},
		{ExternalID: "user_2", Email: "b@example.com"},
	},
	OnConflict: "update",
})
Send Emails
sendResp, err := client.Send(synapse.SendParams{
	TemplateSlug: "welcome",
	To:           map[string]interface{}{"email": "jane@example.com"},
	Attributes:   map[string]interface{}{"name": "Jane"},
})
Manage Contacts
// List contacts
list, err := client.Contacts.List(synapse.ContactListParams{
	Page:    1,
	PerPage: 25,
})

// Get a contact
contact, err := client.Contacts.Get("contact_id")

// Update a contact
updated, err := client.Contacts.Update("external_id", synapse.ContactUpdateParams{
	Email: "new@example.com",
	AddTags: []string{"vip"},
})

// Delete a contact
err = client.Contacts.Delete("external_id")
Manage Templates
// List templates
templates, err := client.Templates.List()

// Get a template
tmpl, err := client.Templates.Get("welcome")

// Create a template
created, err := client.Templates.Create(synapse.TemplateCreateParams{
	Name:       "Welcome Email",
	Slug:       "welcome",
	Subject:    "Welcome, {{contact.first_name}}!",
	BodyHTML:   "<h1>Welcome!</h1>",
	SenderName: "PYRX",
	FromEmail:  "hello@pyrx.tech",
})

// Update a template
updated, err := client.Templates.Update("welcome", synapse.TemplateUpdateParams{
	Subject: "Updated Subject",
})

// Delete a template
err = client.Templates.Delete("welcome")

// Preview a template
preview, err := client.Templates.Preview("welcome", synapse.TemplatePreviewParams{
	Contact: map[string]interface{}{"first_name": "Jane"},
})
Verify Webhooks
result, err := synapse.VerifyWebhook(
	rawBodyString,
	map[string]string{
		"svix-id":        r.Header.Get("svix-id"),
		"svix-timestamp": r.Header.Get("svix-timestamp"),
		"svix-signature": r.Header.Get("svix-signature"),
	},
	"whsec_your_webhook_secret",
	false, // disableTimestampCheck
)
if err != nil {
	// Signature verification failed
	log.Printf("Webhook verification failed: %v", err)
	return
}
// result is a map[string]interface{} with the parsed event
Error Handling
resp, err := client.Track(synapse.TrackParams{
	ExternalID: "user_123",
	EventName:  "test",
})
if err != nil {
	switch e := err.(type) {
	case *synapse.SynapseAuthError:
		log.Printf("Authentication failed: %s", e.Message)
	case *synapse.SynapseRateLimitError:
		log.Printf("Rate limited, retry after: %.0fs", e.RetryAfter)
	case *synapse.SynapsePlanLimitError:
		log.Printf("Plan limit reached: %s (%d/%d on %s plan)",
			e.LimitType, e.Current, e.Maximum, e.Plan)
	case *synapse.SynapseValidationError:
		for _, fieldErr := range e.Errors {
			log.Printf("Validation error on %s: %s", fieldErr.Field, fieldErr.Message)
		}
	case *synapse.SynapseError:
		log.Printf("API error %d: %s", e.Status, e.Message)
	default:
		log.Printf("Unexpected error: %v", err)
	}
}

Retry Logic

The SDK automatically retries on:

  • HTTP 429 (Too Many Requests) - uses Retry-After header when available
  • HTTP 500, 502, 503, 504 (Server Errors)
  • Network errors (timeouts, connection refused)

Backoff: min(1.0 * 2^attempt, 30.0) + random(0, 0.5) seconds.

Non-retryable errors (401, 403, 422) are returned immediately.

Environment Detection

The SDK auto-detects your environment from the API key prefix:

  • psk_test_* -> "test"
  • psk_live_* -> "live"
  • Other -> "unknown"

Access via client.Environment.

Requirements

  • Go 1.21+
  • No external dependencies (stdlib only)

License

MIT

Documentation

Index

Constants

View Source
const Version = "0.1.0"

Version is the SDK version string.

Variables

This section is empty.

Functions

func MapError

func MapError(status int, body map[string]interface{}, retryAfter float64) error

MapError maps an HTTP status code and response body to the appropriate error type.

func VerifyWebhook

func VerifyWebhook(payload string, headers map[string]string, secret string, disableTimestampCheck bool) (map[string]interface{}, error)

VerifyWebhook verifies a webhook signature from Synapse (Svix format) and returns the parsed payload. Set disableTimestampCheck to true to skip timestamp tolerance validation (for testing only).

Types

type BatchTrackResponse

type BatchTrackResponse struct {
	Accepted int `json:"accepted"`
	Rejected int `json:"rejected"`
}

BatchTrackResponse is the response from a batch track call.

type BulkContactResponse

type BulkContactResponse struct {
	Total   int                      `json:"total"`
	Created int                      `json:"created"`
	Updated int                      `json:"updated"`
	Skipped int                      `json:"skipped"`
	Errors  []map[string]interface{} `json:"errors"`
}

BulkContactResponse is the response from a bulk contact operation.

type Client

type Client struct {
	Environment string
	Contacts    *ContactsClient
	Templates   *TemplatesClient
	// contains filtered or unexported fields
}

Client is the main Synapse API client.

func NewClient

func NewClient(config Config) (*Client, error)

NewClient creates a new Synapse client with the given configuration.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the configured base URL.

func (*Client) Identify

func (c *Client) Identify(params IdentifyParams) (*ContactResponse, error)

Identify creates or updates a contact.

func (*Client) IdentifyBatch

func (c *Client) IdentifyBatch(params IdentifyBatchParams) (*BulkContactResponse, error)

IdentifyBatch creates or updates multiple contacts.

func (*Client) Send

func (c *Client) Send(params SendParams) (*SendResponse, error)

Send sends an email using a template.

func (*Client) Track

func (c *Client) Track(params TrackParams) (*TrackResponse, error)

Track tracks a single event.

func (*Client) TrackBatch

func (c *Client) TrackBatch(params TrackBatchParams) (*BatchTrackResponse, error)

TrackBatch tracks multiple events in a single request.

type Config

type Config struct {
	APIKey      string
	WorkspaceID string
	BaseURL     string        // default: "https://synapse-api.pyrx.tech"
	Timeout     time.Duration // default: 30s
	MaxRetries  int           // default: 3
}

Config holds the configuration for a Synapse client.

type ContactListMeta

type ContactListMeta struct {
	Total      int `json:"total"`
	Page       int `json:"page"`
	PerPage    int `json:"per_page"`
	TotalPages int `json:"total_pages"`
}

ContactListMeta holds pagination metadata.

type ContactListParams

type ContactListParams struct {
	Search    string
	Page      int
	PerPage   int
	SortBy    string
	SortOrder string
}

ContactListParams holds the query parameters for listing contacts.

type ContactListResponse

type ContactListResponse struct {
	Data []ContactResponse `json:"data"`
	Meta ContactListMeta   `json:"meta"`
}

ContactListResponse is the response from listing contacts.

type ContactResponse

type ContactResponse struct {
	ID         string                 `json:"id"`
	ExternalID string                 `json:"external_id"`
	Email      string                 `json:"email"`
	Phone      string                 `json:"phone"`
	FirstName  string                 `json:"first_name"`
	LastName   string                 `json:"last_name"`
	Timezone   string                 `json:"timezone"`
	Locale     string                 `json:"locale"`
	Properties map[string]interface{} `json:"properties"`
	Tags       []string               `json:"tags"`
	CreatedAt  string                 `json:"created_at"`
	UpdatedAt  string                 `json:"updated_at"`
}

ContactResponse is the response containing contact data.

type ContactUpdateParams

type ContactUpdateParams struct {
	Email      string                 `json:"email,omitempty"`
	Properties map[string]interface{} `json:"properties,omitempty"`
	Tags       []string               `json:"tags,omitempty"`
	AddTags    []string               `json:"add_tags,omitempty"`
	RemoveTags []string               `json:"remove_tags,omitempty"`
}

ContactUpdateParams holds the parameters for updating a contact.

type ContactsClient

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

ContactsClient provides methods for managing contacts.

func (*ContactsClient) Delete

func (cc *ContactsClient) Delete(externalID string) error

Delete removes a contact by external ID.

func (*ContactsClient) Get

func (cc *ContactsClient) Get(contactID string) (*ContactResponse, error)

Get retrieves a single contact by ID.

func (*ContactsClient) List

List returns a paginated list of contacts.

func (*ContactsClient) Update

func (cc *ContactsClient) Update(externalID string, params ContactUpdateParams) (*ContactResponse, error)

Update updates a contact by external ID.

type IdentifyBatchParams

type IdentifyBatchParams struct {
	Contacts   []IdentifyParams `json:"contacts"`
	OnConflict string           `json:"on_conflict,omitempty"`
}

IdentifyBatchParams holds the parameters for batch identifying contacts.

type IdentifyParams

type IdentifyParams struct {
	ExternalID string                 `json:"external_id"`
	Email      string                 `json:"email,omitempty"`
	Phone      string                 `json:"phone,omitempty"`
	FirstName  string                 `json:"first_name,omitempty"`
	LastName   string                 `json:"last_name,omitempty"`
	Timezone   string                 `json:"timezone,omitempty"`
	Locale     string                 `json:"locale,omitempty"`
	Properties map[string]interface{} `json:"properties,omitempty"`
	Tags       []string               `json:"tags,omitempty"`
}

IdentifyParams holds the parameters for identifying a contact.

type SendParams

type SendParams struct {
	TemplateSlug   string                 `json:"template_slug"`
	To             map[string]interface{} `json:"to"`
	Attributes     map[string]interface{} `json:"attributes,omitempty"`
	IdempotencyKey string                 `json:"idempotency_key,omitempty"`
}

SendParams holds the parameters for sending an email.

type SendResponse

type SendResponse struct {
	EmailLogID string `json:"email_log_id"`
	Status     string `json:"status"`
}

SendResponse is the response from a send email call.

type SynapseAuthError

type SynapseAuthError struct {
	SynapseError
}

SynapseAuthError is raised on 401 Unauthorized or 403 Forbidden.

type SynapseError

type SynapseError struct {
	Message   string
	Status    int
	Code      string
	RequestID string
}

SynapseError is the base error for all Synapse API errors.

func (*SynapseError) Error

func (e *SynapseError) Error() string

type SynapsePlanLimitError

type SynapsePlanLimitError struct {
	SynapseError
	LimitType string
	Current   int
	Maximum   int
	Plan      string
}

SynapsePlanLimitError is raised on 403 with code "plan_limit_reached".

type SynapseRateLimitError

type SynapseRateLimitError struct {
	SynapseError
	RetryAfter float64
}

SynapseRateLimitError is raised on 429 Too Many Requests.

type SynapseValidationError

type SynapseValidationError struct {
	SynapseError
	Errors []ValidationFieldError
}

SynapseValidationError is raised on 422 Unprocessable Entity.

type TemplateCreateParams

type TemplateCreateParams struct {
	Name       string `json:"name"`
	Slug       string `json:"slug"`
	Subject    string `json:"subject"`
	BodyHTML   string `json:"body_html"`
	SenderName string `json:"sender_name"`
	FromEmail  string `json:"from_email"`
	ReplyTo    string `json:"reply_to,omitempty"`
}

TemplateCreateParams holds the parameters for creating a template.

type TemplatePreviewParams

type TemplatePreviewParams struct {
	Contact          map[string]interface{}   `json:"contact,omitempty"`
	TriggerEvent     map[string]interface{}   `json:"trigger_event,omitempty"`
	AdditionalEvents []map[string]interface{} `json:"additional_events,omitempty"`
}

TemplatePreviewParams holds the parameters for previewing a template.

type TemplatePreviewResponse

type TemplatePreviewResponse struct {
	Subject          string `json:"subject"`
	HTML             string `json:"html"`
	Suppressed       bool   `json:"suppressed"`
	SuppressedReason string `json:"suppressed_reason"`
}

TemplatePreviewResponse is the response from previewing a template.

type TemplateResponse

type TemplateResponse struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Slug        string `json:"slug"`
	Subject     string `json:"subject"`
	BodyHTML    string `json:"body_html"`
	SenderName  string `json:"sender_name"`
	FromEmail   string `json:"from_email"`
	ReplyTo     string `json:"reply_to"`
	ContentType string `json:"content_type"`
	CreatedAt   string `json:"created_at"`
	UpdatedAt   string `json:"updated_at"`
}

TemplateResponse is the response containing template data.

type TemplateUpdateParams

type TemplateUpdateParams struct {
	Name       string `json:"name,omitempty"`
	Subject    string `json:"subject,omitempty"`
	BodyHTML   string `json:"body_html,omitempty"`
	SenderName string `json:"sender_name,omitempty"`
	FromEmail  string `json:"from_email,omitempty"`
}

TemplateUpdateParams holds the parameters for updating a template.

type TemplatesClient

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

TemplatesClient provides methods for managing email templates.

func (*TemplatesClient) Create

Create creates a new email template.

func (*TemplatesClient) Delete

func (tc *TemplatesClient) Delete(slug string) error

Delete removes a template by slug.

func (*TemplatesClient) Get

func (tc *TemplatesClient) Get(slug string) (*TemplateResponse, error)

Get retrieves a single template by slug.

func (*TemplatesClient) List

func (tc *TemplatesClient) List() ([]TemplateResponse, error)

List returns all email templates.

func (*TemplatesClient) Preview

Preview renders a template with sample data.

func (*TemplatesClient) Update

func (tc *TemplatesClient) Update(slug string, params TemplateUpdateParams) (*TemplateResponse, error)

Update updates an existing template by slug.

type TrackBatchParams

type TrackBatchParams struct {
	Events []TrackParams `json:"events"`
}

TrackBatchParams holds the parameters for tracking multiple events.

type TrackParams

type TrackParams struct {
	ExternalID     string                 `json:"external_id"`
	EventName      string                 `json:"event_name"`
	Attributes     map[string]interface{} `json:"attributes,omitempty"`
	Contact        map[string]interface{} `json:"contact,omitempty"`
	IdempotencyKey string                 `json:"idempotency_key,omitempty"`
	OccurredAt     string                 `json:"occurred_at,omitempty"`
}

TrackParams holds the parameters for tracking an event.

type TrackResponse

type TrackResponse struct {
	EventID string `json:"event_id"`
	Status  string `json:"status"`
}

TrackResponse is the response from tracking a single event.

type ValidationFieldError

type ValidationFieldError struct {
	Field   string
	Message string
}

ValidationFieldError represents a single field validation error.

Jump to

Keyboard shortcuts

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