agilisads

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 22 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Agilis Advertising API for Go

The official Go client for the Agilis Advertising REST API: create and manage Offers, publish Events, and receive webhooks.

  • Go 1.22 or later
  • Standard library only

Install

go get github.com/agilisdating/agilis-ads-go
import agilisads "github.com/agilisdating/agilis-ads-go"

Quick start in Test mode

Create a Test key in the Ad Portal (Manage API Keys, in Test mode). Test Offers and Events are never shown to members and nothing is charged.

package main

import (
	"context"
	"fmt"
	"log"

	agilisads "github.com/agilisdating/agilis-ads-go"
)

func main() {
	client := agilisads.NewClient("") // reads AGILIS_API_KEY
	if client.Mode() != agilisads.ModeTest {
		log.Fatal("use a Test key")
	}

	categories, err := client.Categories.List(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	for _, c := range categories.Categories {
		fmt.Println(c.CategoryID, c.CategoryName)
	}
}

More in examples/: a Test-mode script and a webhook receiver.

The client

client := agilisads.NewClient(apiKey,
	agilisads.WithBaseURL("https://ads.agilis.dating"), // the default
	agilisads.WithTimeout(60*time.Second),              // per attempt; the default
	agilisads.WithMaxRetries(2),                        // the default
	agilisads.WithHTTPClient(&http.Client{}),           // any *http.Client
)
  • API key: pass it, or pass "" to read AGILIS_API_KEY. Keep keys in environment variables or a secrets manager, never in code.
  • Mode: the key decides it: pk_test_ is Test and pk_live_ is Live. client.Mode() returns agilisads.ModeTest or agilisads.ModeLive, so you can refuse to run against Live. Operations that take an Environment fill it in from the key when you leave it empty.
  • The key is sent in the x-api-key header only. It is never logged, never part of a URL and never in an error message.
  • A *Client is safe for concurrent use.

Resources and methods

Every method takes a context.Context, then any path parameters, then a parameters struct where the operation has parameters. Optional fields are pointers; use the helpers agilisads.String, Int, Int64, Float64 and Bool.

Resource Method HTTP
client.Categories List(ctx) GET /categories
client.Interests List(ctx) GET /interests
client.Offers EstimatePrice(ctx, *EstimateOfferPriceParams) POST /offers/price-estimate
Create(ctx, *CreateOfferParams) POST /offers
List(ctx, *ListOffersParams) GET /offers
ListAutoPaging(ctx, *ListOffersParams) every page of GET /offers
Pause(ctx, offerID) POST /offers/{offer_id}/pause
Resume(ctx, offerID) POST /offers/{offer_id}/resume
Analytics(ctx, offerID, *AnalyticsParams) GET /offers/{offer_id}/analytics
Delete(ctx, offerID, *DeleteParams) DELETE /offers/{offer_id}
client.EventCategories List(ctx) GET /event-categories
client.EventCurrencies List(ctx) GET /event-currencies
client.EventConfig Get(ctx) GET /event-config
client.Events Preview(ctx, *PreviewEventParams) POST /events/preview
Publish(ctx, *PublishEventParams) POST /events
List(ctx, *ListEventsParams) GET /events
ListAutoPaging(ctx, *ListEventsParams) every page of GET /events
Get(ctx, eventID) GET /events/{event_id}
Edit(ctx, eventID, *EditEventParams) PATCH /events/{event_id}, sent as POST with X-HTTP-Method-Override: PATCH
Delete(ctx, eventID, *DeleteParams) DELETE /events/{event_id}
Reschedule(ctx, eventID, *RescheduleEventParams) POST /events/{event_id}/reschedule
Cancel(ctx, eventID, *DeleteParams) POST /events/{event_id}/cancel
Analytics(ctx, eventID, *AnalyticsParams) GET /events/{event_id}/analytics
client.WebhookEndpoints List(ctx) GET /webhook-endpoints
Create(ctx, *CreateWebhookEndpointParams) POST /webhook-endpoints
Get(ctx, endpointID) GET /webhook-endpoints/{endpoint_id}
Update(ctx, endpointID, *UpdateWebhookEndpointParams) PATCH /webhook-endpoints/{endpoint_id}
Delete(ctx, endpointID) DELETE /webhook-endpoints/{endpoint_id}
RollSecret(ctx, endpointID, *RollWebhookSecretParams) POST /webhook-endpoints/{endpoint_id}/roll-secret
SendTest(ctx, endpointID, *SendTestWebhookParams) POST /webhook-endpoints/{endpoint_id}/test
client.WebhookEvents List(ctx, *ListWebhookEventsParams) GET /webhook-events
ListAutoPaging(ctx, *ListWebhookEventsParams) every page of GET /webhook-events
Get(ctx, webhookEventID) GET /webhook-events/{webhook_event_id}
Resend(ctx, webhookEventID, *ResendWebhookEventParams) POST /webhook-events/{webhook_event_id}/resend
package ConstructEvent(payload, header, secret, ...WebhookOption) verifies a received webhook

The field names and rules are those of the API reference.

Creating an Offer
res, err := client.Offers.Create(ctx, &agilisads.CreateOfferParams{
	CategoryID:              1,
	Title:                   "20% off summer sale",
	Description:             "Discount valid through July",
	PushNotificationTitle:   "20% off this summer",
	PushNotificationMessage: "Show this at the till for 20% off everything.",
	ButtonPreset:            agilisads.ButtonBookNow,
	URL:                     "https://www.example.com/offer",
	Image:                   agilisads.FileFromPath("offer.png"),
	Location:                agilisads.LatLng{Latitude: 51.5074, Longitude: -0.1278},
	Radius:                  10,
	Gender:                  []string{agilisads.GenderFemale},
	Interests:               []int64{3, 7},
	StartDatetime:           "2027-07-10T08:00:00Z",
	ExpiryDatetime:          "2027-07-12T20:30:00Z",
	PaymentMethod:           agilisads.PaymentMethodBalance,
	DryRun:                  true, // check the cost first; nothing is created
})

An image can be FileFromPath(path), FileFromBytes(name, data) or FileFromReader(name, r). The content type comes from the file name (.jpg, .png, .gif); set it with WithContentType if the name has none.

Array fields are sent as repeated location[], gender[] and interests[] parts, and an Event crop as crop[x], crop[y] and crop[w].

Responses

Each method returns a typed struct. Every response embeds agilisads.Response:

res.StatusCode             // the HTTP status
res.Header.Get("X-RateLimit-Remaining")
res.RateLimitRemaining()   // the same, as an int (-1 when absent)
res.RawJSON                // the body as received
res.Field("balance_after") // the raw JSON of any top-level field

Fields the SDK does not know yet never break decoding: they stay in RawJSON. A dry run's figures (price, balance_after, amount_to_charge and so on) are read with Field.

Pagination

List returns one page. ListAutoPaging follows next_cursor until has_more is false:

it := client.Offers.ListAutoPaging(ctx, &agilisads.ListOffersParams{OfferStatus: "active"})
for it.Next() {
	offer := it.Current()
	fmt.Println(offer.OfferID, offer.Title)
}
if err := it.Err(); err != nil {
	log.Fatal(err)
}

Idempotency and retries

  • Offers.Create and Events.Publish send an Idempotency-Key: yours (IdempotencyKey) or a random UUID v4, generated once per call and reused on every retry. The response's IdempotencyKey is the key that was sent.
  • DryRun: true on Offers.Create and Events.Publish, and &agilisads.DeleteParams{DryRun: true} on Offers.Delete, Events.Delete and Events.Cancel, send dry_run=true: nothing is created, changed or charged.
  • Retried (up to WithMaxRetries, default 2): connection errors and timeouts; HTTP 429; and HTTP 500, 502, 503 and 504 for GET and DELETE, and for a POST that carries an Idempotency-Key.
  • Not retried: other POST and PATCH requests on a 5xx, because the change may have happened.
  • The wait: Retry-After when the API sends it; otherwise 0.5 s × 2^attempt with ±25% jitter, at most 8 s. A cancelled context stops the retries.

Errors

Every API error unwraps to *agilisads.AgilisError, which carries StatusCode, ReturnCode, Message, Body, Data (the parsed body) and Header. Check for a specific kind with errors.As:

Type When
*AuthenticationError 401
*PermissionError 403
*NotFoundError 404
*ConflictError 409
*InvalidRequestError 400, 422, and a refusal that arrives as HTTP 200 with a return_code starting with E
*RateLimitError 429, with RetryAfter
*APIError 5xx and anything else
*ConnectionError no response (Err holds the cause)
*SignatureVerificationError ConstructEvent, with Reason
_, err := client.Offers.Create(ctx, params)
var invalid *agilisads.InvalidRequestError
if errors.As(err, &invalid) && invalid.ReturnCode == "E3" {
	// the balance is too low: top up and retry with the same IdempotencyKey
}

Some refusals come as HTTP 200 with an E code (for example E3, balance too low): these are *InvalidRequestError with StatusCode 200. S1 and S2 are both success.

Webhooks

ConstructEvent checks the Agilis-Signature header against the raw body with your endpoint's secret, in constant time, accepting any matching v1 (there are two while a secret is being rolled) and a timestamp within 5 minutes. It returns the event, or a *SignatureVerificationError.

http.HandleFunc("/agilis/webhooks", func(w http.ResponseWriter, r *http.Request) {
	payload, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
	event, err := agilisads.ConstructEvent(payload, r.Header.Get(agilisads.SignatureHeader), secret)
	if err != nil {
		http.Error(w, "invalid signature", http.StatusBadRequest)
		return
	}
	w.WriteHeader(http.StatusNoContent) // answer quickly, then do the work

	switch event.Type {
	case agilisads.EventTypeOfferStarted:
		offer, _ := event.Data.Offer()
		log.Println("offer started:", offer.OfferID)
	case agilisads.EventTypeEventPublished:
		ev, _ := event.Data.Event()
		log.Println("event published:", ev.EventID)
	}
})
  • Pass the body exactly as received: do not decode and re-encode it first.
  • event.Data.Object is the raw data.object; event.Data.Offer(), event.Data.Event() and event.Data.DecodeObject(&v) decode it, and event.Data.Fields holds every field of data, such as amount_charged.
  • Options: agilisads.WithTolerance(d) (default 5 minutes) and agilisads.WithNow(f). VerifySignature checks without decoding.
  • Use event.ID to ignore repeats and event.Created to order events.

Tests

go test -race ./...

The Test-mode run uses a Test key and creates nothing that lasts: it reads, and sends an Offer create and an Event publish as dry runs. It refuses to run with a Live key.

AGILIS_TEST_API_KEY=pk_test_... go test -tags integration -run Integration ./...

Licence

MIT. See LICENSE. To report a security problem, see SECURITY.md.

Documentation

Overview

Package agilisads is the official Go client for the Agilis Advertising REST API.

Create a client with an API key (or leave it empty to read AGILIS_API_KEY from the environment) and call the operations grouped by resource:

client := agilisads.NewClient("pk_test_...")
categories, err := client.Categories.List(ctx)

The key decides the mode: a pk_test_ key works in TEST mode and a pk_live_ key in LIVE mode. Operations that take an environment fill it in from the key when it is left empty.

Index

Constants

View Source
const (
	GenderMale      = "Male"
	GenderFemale    = "Female"
	GenderNonBinary = "Non-binary"
	GenderAll       = "All"
)

Gender values for Offer targeting.

View Source
const (
	// PaymentMethodLink sends a Stripe payment link by email (Offers only).
	PaymentMethodLink = "E"

	// PaymentMethodBalance deducts the price from the balance of the mode.
	PaymentMethodBalance = "B"
)

Payment methods. An Event can only be paid from the balance.

View Source
const (
	ButtonClaimOffer    = "claim_offer"
	ButtonVisitWebsite  = "visit_website"
	ButtonInstallApp    = "install_app"
	ButtonBookNow       = "book_now"
	ButtonGetDirections = "get_directions"
	ButtonCustom        = "custom"
)

Button presets for an Offer's button.

View Source
const (
	Interval24Hours = "24h"
	Interval7Days   = "7d"
	Interval30Days  = "30d"
	Interval60Days  = "60d"
	Interval90Days  = "90d"
	IntervalAll     = "all"
)

Analytics intervals.

View Source
const (
	EventTypeAll                   = "*"
	EventTypeOfferCreated          = "offer.created"
	EventTypeOfferPaymentSucceeded = "offer.payment_succeeded"
	EventTypeOfferPaymentFailed    = "offer.payment_failed"
	EventTypeOfferStarted          = "offer.started"
	EventTypeOfferPaused           = "offer.paused"
	EventTypeOfferResumed          = "offer.resumed"
	EventTypeOfferEnded            = "offer.ended"
	EventTypeOfferDeleted          = "offer.deleted"
	EventTypeOfferDisabled         = "offer.disabled"
	EventTypeOfferEnabled          = "offer.enabled"
	EventTypeEventPublished        = "event.published"
	EventTypeEventUpdated          = "event.updated"
	EventTypeEventRescheduled      = "event.rescheduled"
	EventTypeEventCancelled        = "event.cancelled"
	EventTypeEventDeleted          = "event.deleted"
	EventTypeEventEnded            = "event.ended"
	EventTypeBalanceToppedUp       = "balance.topped_up"
	EventTypeBalanceLow            = "balance.low"
	EventTypeInvoiceCreated        = "invoice.created"
	EventTypeTermsVersionIssued    = "terms.version_issued"
)

Webhook event types.

View Source
const DefaultBaseURL = "https://ads.agilis.dating"

DefaultBaseURL is the address of the Agilis Advertising API.

View Source
const DefaultMaxRetries = 2

DefaultMaxRetries is how many times a failed request is retried.

View Source
const DefaultTimeout = 60 * time.Second

DefaultTimeout is how long a single attempt may take before it is abandoned.

View Source
const DefaultTolerance = 300 * time.Second

DefaultTolerance is how far a webhook timestamp may be from now.

View Source
const SignatureHeader = "Agilis-Signature"

SignatureHeader is the header that carries a webhook message's signature.

View Source
const Version = "0.1.0"

Version is the version of this module.

Variables

View Source
var ErrNoAPIKey = errors.New("agilisads: no API key: pass one to NewClient or set AGILIS_API_KEY")

ErrNoAPIKey is returned by every operation when the client has no API key: none was passed to NewClient and AGILIS_API_KEY is not set.

Functions

func Bool

func Bool(v bool) *bool

Bool returns a pointer to v, for optional parameters.

func Float64

func Float64(v float64) *float64

Float64 returns a pointer to v, for optional parameters.

func Int

func Int(v int) *int

Int returns a pointer to v, for optional parameters.

func Int64

func Int64(v int64) *int64

Int64 returns a pointer to v, for optional parameters.

func String

func String(v string) *string

String returns a pointer to v, for optional parameters.

func VerifySignature

func VerifySignature(payload []byte, header, secret string, opts ...WebhookOption) error

VerifySignature checks a webhook message's signature without decoding it. It returns nil or a *SignatureVerificationError.

Types

type APIError

type APIError struct{ AgilisError }

APIError is returned for HTTP 5xx and any other unexpected status, and when a successful response cannot be decoded.

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap returns the base error.

type ActionResult

type ActionResult struct {
	Response
	ReturnCode string `json:"return_code"`
	Message    string `json:"message"`
	DryRun     bool   `json:"dry_run"`
}

ActionResult is the response of an action such as pausing or deleting.

type AgilisError

type AgilisError struct {
	// StatusCode is the HTTP status, or 0 when there was no response.
	StatusCode int

	// ReturnCode is the API's return_code, such as "E1", when there is one.
	ReturnCode string

	// Message is the API's message, or a description of the failure.
	Message string

	// Body is the raw response body.
	Body []byte

	// Data is the parsed response body when it is a JSON object.
	Data map[string]any

	// Header holds the response headers.
	Header http.Header
}

AgilisError is the base of every error the API returns. Each error the SDK returns for a failed request is one of the types below, and each of them unwraps to *AgilisError, so either can be used with errors.As:

var nf *agilisads.NotFoundError
if errors.As(err, &nf) { ... }

var ae *agilisads.AgilisError
if errors.As(err, &ae) { fmt.Println(ae.StatusCode, ae.ReturnCode) }

The API key never appears in an error.

func (*AgilisError) Error

func (e *AgilisError) Error() string

type AnalyticsParams

type AnalyticsParams struct {
	// Interval is one of the Interval constants. Required.
	Interval string
}

AnalyticsParams are the parameters of Offers.Analytics and Events.Analytics.

type AuthenticationError

type AuthenticationError struct{ AgilisError }

AuthenticationError is returned for HTTP 401: the key is missing, unknown, disabled or expired.

func (*AuthenticationError) Unwrap

func (e *AuthenticationError) Unwrap() error

Unwrap returns the base error.

type Band

type Band string

Band is a figure the API gives as a band, such as "10-25", never an exact number. It also accepts a JSON number.

func (*Band) UnmarshalJSON

func (b *Band) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts a string, a number or null.

type CancelledEvent

type CancelledEvent struct {
	Response
	ReturnCode string `json:"return_code"`
	Message    string `json:"message"`
	EventID    int64  `json:"event_id"`
	Status     string `json:"status"`
	DryRun     bool   `json:"dry_run"`
}

CancelledEvent is the response of Events.Cancel.

type CategoriesService

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

CategoriesService lists Offer categories.

func (*CategoriesService) List

List returns the Offer categories (GET /categories).

type Category

type Category struct {
	CategoryID   int64  `json:"category_id"`
	CategoryName string `json:"category_name"`
}

Category is an Offer category.

type CategoryList

type CategoryList struct {
	Response
	Categories []Category `json:"categories"`
}

CategoryList is the response of Categories.List.

type Client

type Client struct {
	Categories       *CategoriesService
	Interests        *InterestsService
	Offers           *OffersService
	EventCategories  *EventCategoriesService
	EventCurrencies  *EventCurrenciesService
	EventConfig      *EventConfigService
	Events           *EventsService
	WebhookEndpoints *WebhookEndpointsService
	WebhookEvents    *WebhookEventsService
	// contains filtered or unexported fields
}

Client is a client for the Agilis Advertising API. It is safe for concurrent use.

func NewClient

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

NewClient returns a client that uses apiKey. When apiKey is empty, the key is read from the AGILIS_API_KEY environment variable.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the API address the client sends requests to.

func (*Client) Mode

func (c *Client) Mode() Mode

Mode returns the mode of the client's API key: ModeTest, ModeLive or ModeUnknown. Use it to refuse to run against LIVE.

func (*Client) String

func (c *Client) String() string

String describes the client without its API key.

type ConflictError

type ConflictError struct{ AgilisError }

ConflictError is returned for HTTP 409, for example when an Idempotency-Key is reused while the first request is still being processed.

func (*ConflictError) Unwrap

func (e *ConflictError) Unwrap() error

Unwrap returns the base error.

type ConnectionError

type ConnectionError struct {
	AgilisError

	// Err is the underlying error.
	Err error
}

ConnectionError is returned when no response was received: the connection failed, the attempt timed out or the context ended.

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() []error

Unwrap returns the base error and the underlying error.

type CreateOfferParams

type CreateOfferParams struct {
	CategoryID              int64
	Title                   string
	Description             string
	TermsAndConditions      *string
	AdvertisedName          *string
	PushNotificationTitle   string
	PushNotificationMessage string

	// ButtonPreset is one of the Button constants; empty means claim_offer.
	ButtonPreset string

	// ButtonText is required when ButtonPreset is ButtonCustom.
	ButtonText *string
	URL        string
	Image      *File
	Location   LatLng

	// Radius is in miles.
	Radius    int
	Gender    []string
	Interests []int64

	// StartDatetime and ExpiryDatetime are ISO 8601, UTC.
	StartDatetime  string
	ExpiryDatetime string

	// PaymentMethod is PaymentMethodLink or PaymentMethodBalance.
	PaymentMethod string

	// Environment is filled in from the key when empty.
	Environment Environment

	// IdempotencyKey is generated (a UUID v4) when empty, and reused on
	// every retry of the call.
	IdempotencyKey string

	// DryRun checks everything and answers with the cost, creating nothing.
	DryRun bool
}

CreateOfferParams are the parameters of Offers.Create.

type CreateWebhookEndpointParams

type CreateWebhookEndpointParams struct {
	URL           string   `json:"url"`
	EnabledEvents []string `json:"enabled_events"`
	Description   *string  `json:"description,omitempty"`
}

CreateWebhookEndpointParams are the parameters of WebhookEndpoints.Create.

type CreatedOffer

type CreatedOffer struct {
	Response
	ReturnCode string  `json:"return_code"`
	OfferID    int64   `json:"offer_id"`
	Status     string  `json:"status"`
	PaymentURL *string `json:"payment_url"`
	Currency   string  `json:"currency"`
	DryRun     bool    `json:"dry_run"`

	// IdempotencyKey is the key that was sent.
	IdempotencyKey string `json:"-"`
}

CreatedOffer is the response of Offers.Create. A dry run's price, matching_members, balance_after and card_amount are reachable with Field.

type Crop

type Crop struct {
	X int
	Y int
	W int
}

Crop is the area of an uploaded event image to use: the top-left corner and the width, in pixels. The height is derived from the 16:9 frame.

type CropArea

type CropArea struct {
	X int `json:"x"`
	Y int `json:"y"`
	W int `json:"w"`
	H int `json:"h"`
}

CropArea is the area of an image in use, in pixels.

type DeleteParams

type DeleteParams struct {
	// DryRun answers with what the operation would do, changing nothing.
	DryRun bool
}

DeleteParams are the optional parameters of the delete and cancel operations.

type DeletedWebhookEndpoint

type DeletedWebhookEndpoint struct {
	Response
	ReturnCode string `json:"return_code"`
	ID         string `json:"id"`
	Deleted    bool   `json:"deleted"`
}

DeletedWebhookEndpoint is the response of WebhookEndpoints.Delete.

type EditEventParams

type EditEventParams struct {
	Title       *string
	Description *string
	URL         *string

	// AdvertisedName set to "" goes back to the trading name.
	AdvertisedName *string
	VenueName      *string
	Address        *string
	City           *string
	CountryCode    *string
	Location       *LatLng

	// A price change must send PriceMin, PriceMax and Currency together.
	PriceMin *float64
	PriceMax *float64
	Currency *string

	// ClearPrice sends all three price fields blank, to show no price.
	ClearPrice    bool
	Image         *File
	PreviewToken  *string
	SourceEventID *int64

	// Crop on its own re-frames the existing image; with Image it is the area
	// of the new picture.
	Crop *Crop
}

EditEventParams are the parameters of Events.Edit. Set only the fields to change. Dates cannot be edited: use Events.Reschedule.

type EditedEvent

type EditedEvent struct {
	Response
	ReturnCode    string           `json:"return_code"`
	Message       string           `json:"message"`
	EventID       int64            `json:"event_id"`
	Status        string           `json:"status"`
	Category      EventCategoryRef `json:"category"`
	ChangedFields []string         `json:"changed_fields"`
	Image         string           `json:"image"`
	ImageLarge    string           `json:"image_large"`
	VenueChanged  bool             `json:"venue_changed"`
}

EditedEvent is the response of Events.Edit.

type Environment

type Environment string

Environment is the environment parameter of the API: TEST or LIVE.

const (
	EnvironmentTest Environment = "TEST"
	EnvironmentLive Environment = "LIVE"
)

The environments of the API.

type EstimateOfferPriceParams

type EstimateOfferPriceParams struct {
	StartDatetime string      `json:"start_datetime"`
	EndDatetime   string      `json:"end_datetime"`
	Location      LatLng      `json:"location"`
	Radius        int         `json:"radius"`
	Gender        []string    `json:"gender,omitempty"`
	Interests     []int64     `json:"interests,omitempty"`
	Environment   Environment `json:"environment,omitempty"`
}

EstimateOfferPriceParams are the parameters of Offers.EstimatePrice.

type Event

type Event struct {
	EventID           int64            `json:"event_id"`
	Title             string           `json:"title"`
	Description       string           `json:"description"`
	Category          EventCategoryRef `json:"category"`
	VenueName         string           `json:"venue_name"`
	Address           string           `json:"address"`
	City              string           `json:"city"`
	CountryCode       string           `json:"country_code"`
	Latitude          float64          `json:"latitude"`
	Longitude         float64          `json:"longitude"`
	StartsAt          string           `json:"starts_at"`
	EndsAt            string           `json:"ends_at"`
	URL               string           `json:"url"`
	AdvertisedName    *string          `json:"advertised_name"`
	PriceMin          *float64         `json:"price_min"`
	PriceMax          *float64         `json:"price_max"`
	Currency          *string          `json:"currency"`
	Image             string           `json:"image"`
	ImageLarge        string           `json:"image_large"`
	ImageThumb        string           `json:"image_thumb"`
	EventStatus       string           `json:"event_status"`
	Attendees         Band             `json:"attendees"`
	Owner             *EventOwner      `json:"owner"`
	Environment       string           `json:"environment"`
	RescheduleCount   int              `json:"reschedule_count"`
	ClonedFromEventID *int64           `json:"cloned_from_event_id"`
	CreationDatetime  string           `json:"creation_datetime"`
	LastEditedAt      *string          `json:"last_edited_at"`
}

Event is an Event as the list returns it.

type EventAnalytics

type EventAnalytics struct {
	Response
	EventID  int64        `json:"event_id"`
	Interval string       `json:"interval"`
	StartsAt string       `json:"starts_at"`
	EndsAt   string       `json:"ends_at"`
	Status   string       `json:"status"`
	Metrics  EventMetrics `json:"metrics"`

	// AsOf is when the figures were refreshed, nil until the first member
	// interaction.
	AsOf *string `json:"as_of"`
}

EventAnalytics is the response of Events.Analytics.

type EventCategoriesService

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

EventCategoriesService lists Event categories.

func (*EventCategoriesService) List

List returns the Event categories (GET /event-categories).

type EventCategory

type EventCategory struct {
	CategoryID   int64  `json:"category_id"`
	Code         string `json:"code"`
	CategoryName string `json:"category_name"`
}

EventCategory is an Event category.

type EventCategoryList

type EventCategoryList struct {
	Response
	Categories []EventCategory `json:"categories"`
}

EventCategoryList is the response of EventCategories.List.

type EventCategoryRef

type EventCategoryRef struct {
	CategoryID   int64  `json:"category_id"`
	CategoryName string `json:"category_name"`
}

EventCategoryRef is the category determined for an Event.

type EventConfig

type EventConfig struct {
	Response

	// ListingFee, Currency, ExchangeRatePerGBP and ExchangeRateDate are nil
	// when the billing currency cannot be billed right now.
	ListingFee          *float64         `json:"listing_fee"`
	Currency            *string          `json:"currency"`
	ExchangeRatePerGBP  *float64         `json:"exchange_rate_per_gbp"`
	ExchangeRateDate    *string          `json:"exchange_rate_date"`
	Environment         string           `json:"environment"`
	Balance             float64          `json:"balance"`
	OrganisationBalance float64          `json:"organisation_balance"`
	LivePublishingOpen  bool             `json:"live_publishing_open"`
	Currencies          []string         `json:"currencies"`
	Image               EventImageLimits `json:"image"`
	MaxYearsAhead       int              `json:"max_years_ahead"`
}

EventConfig is the response of EventConfig.Get: what publishing an Event costs, the balance of the key's mode and the image limits.

type EventConfigService

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

EventConfigService reads the Event configuration.

func (*EventConfigService) Get

Get returns the Event configuration (GET /event-config).

type EventCurrenciesService

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

EventCurrenciesService lists the currencies an Event's ticket price can use.

func (*EventCurrenciesService) List

List returns the currencies an Event's ticket price can use (GET /event-currencies).

type EventCurrencyList

type EventCurrencyList struct {
	Response
	Currencies []string `json:"currencies"`
}

EventCurrencyList is the response of EventCurrencies.List.

type EventDetails

type EventDetails struct {
	Response
	Event
	CanManage            bool                `json:"can_manage"`
	CanDelete            bool                `json:"can_delete"`
	ListingPrice         *float64            `json:"listing_price"`
	BillingCurrency      *string             `json:"billing_currency"`
	InvoiceID            *string             `json:"invoice_id"`
	AppSyncedAt          *string             `json:"app_synced_at"`
	HasMemberInteraction bool                `json:"has_member_interaction"`
	ImageMaster          *EventImageMaster   `json:"image_master"`
	History              []EventHistoryEntry `json:"history"`
}

EventDetails is the response of Events.Get: every field of the list row, plus the cost, permissions, image and history.

type EventHistoryEntry

type EventHistoryEntry struct {
	Action        string          `json:"action"`
	Channel       string          `json:"channel"`
	ActedByUserID *int64          `json:"acted_by_user_id"`
	ActedBy       *string         `json:"acted_by"`
	Details       json.RawMessage `json:"details"`
	Acknowledged  bool            `json:"acknowledged"`
	At            string          `json:"at"`
}

EventHistoryEntry is one action taken on an Event.

type EventImageLimits

type EventImageLimits struct {
	MaxMB     float64 `json:"max_mb"`
	MinWidth  int     `json:"min_width"`
	MinHeight int     `json:"min_height"`
}

EventImageLimits are the limits on an Event image.

type EventImageMaster

type EventImageMaster struct {
	Width  int      `json:"width"`
	Height int      `json:"height"`
	Crop   CropArea `json:"crop"`
	URL    *string  `json:"url"`
}

EventImageMaster is the stored original of an Event image.

type EventList

type EventList struct {
	Response
	Data       []Event    `json:"data"`
	Pagination Pagination `json:"pagination"`
}

EventList is one page of Events.

type EventMetrics

type EventMetrics struct {
	Clicks          int64 `json:"clicks"`
	Attendees       Band  `json:"attendees"`
	InvitesSent     Band  `json:"invites_sent"`
	InvitesAccepted Band  `json:"invites_accepted"`
}

EventMetrics are an Event's figures. Clicks is exact; the others are bands.

type EventOwner

type EventOwner struct {
	UserID int64  `json:"user_id"`
	Name   string `json:"name"`
}

EventOwner is the user who published an Event.

type EventPreview

type EventPreview struct {
	Response
	ReturnCode         string             `json:"return_code"`
	Category           EventCategoryRef   `json:"category"`
	ListingFee         *float64           `json:"listing_fee"`
	Currency           string             `json:"currency"`
	Balance            float64            `json:"balance"`
	BalanceAfter       float64            `json:"balance_after"`
	BalanceSufficient  bool               `json:"balance_sufficient"`
	LivePublishingOpen bool               `json:"live_publishing_open"`
	PriceGBP           *float64           `json:"price_gbp"`
	Image              *EventPreviewImage `json:"image"`
}

EventPreview is the response of Events.Preview.

type EventPreviewImage

type EventPreviewImage struct {
	PreviewURL   string   `json:"preview_url"`
	Width        int      `json:"width"`
	Height       int      `json:"height"`
	MasterWidth  int      `json:"master_width"`
	MasterHeight int      `json:"master_height"`
	Crop         CropArea `json:"crop"`

	// PreviewToken can be passed to Events.Publish instead of the image.
	PreviewToken string `json:"preview_token"`
	ExpiresAt    string `json:"expires_at"`
}

EventPreviewImage is the processed image of a preview.

type EventsService

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

EventsService publishes and manages Events.

func (*EventsService) Analytics

func (s *EventsService) Analytics(ctx context.Context, eventID int64, params *AnalyticsParams) (*EventAnalytics, error)

Analytics returns an Event's figures over an interval (GET /events/{event_id}/analytics).

func (*EventsService) Cancel

func (s *EventsService) Cancel(ctx context.Context, eventID int64, params *DeleteParams) (*CancelledEvent, error)

Cancel cancels an Event (POST /events/{event_id}/cancel). params may be nil.

func (*EventsService) Delete

func (s *EventsService) Delete(ctx context.Context, eventID int64, params *DeleteParams) (*ActionResult, error)

Delete deletes an Event (DELETE /events/{event_id}). params may be nil.

func (*EventsService) Edit

func (s *EventsService) Edit(ctx context.Context, eventID int64, params *EditEventParams) (*EditedEvent, error)

Edit changes a published Event, free of charge (PATCH /events/{event_id}). It is always sent as a multipart POST with X-HTTP-Method-Override: PATCH, with or without an image.

func (*EventsService) Get

func (s *EventsService) Get(ctx context.Context, eventID int64) (*EventDetails, error)

Get returns one Event (GET /events/{event_id}).

func (*EventsService) List

func (s *EventsService) List(ctx context.Context, params *ListEventsParams) (*EventList, error)

List returns one page of Events (GET /events).

func (*EventsService) ListAutoPaging

func (s *EventsService) ListAutoPaging(ctx context.Context, params *ListEventsParams) *Iter[Event]

ListAutoPaging returns an iterator over every Event, following next_cursor until has_more is false.

func (*EventsService) Preview

func (s *EventsService) Preview(ctx context.Context, params *PreviewEventParams) (*EventPreview, error)

Preview shows what publishing would do, without publishing or charging (POST /events/preview).

func (*EventsService) Publish

func (s *EventsService) Publish(ctx context.Context, params *PublishEventParams) (*PublishedEvent, error)

Publish publishes an Event, paid from the balance (POST /events).

func (*EventsService) Reschedule

func (s *EventsService) Reschedule(ctx context.Context, eventID int64, params *RescheduleEventParams) (*RescheduledEvent, error)

Reschedule moves an Event to new dates (POST /events/{event_id}/reschedule).

type File

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

File is an image to upload. Create one with FileFromPath, FileFromBytes or FileFromReader. The content type is detected from the file name unless set with WithContentType.

func FileFromBytes

func FileFromBytes(name string, data []byte) *File

FileFromBytes uploads data with the given file name.

func FileFromPath

func FileFromPath(path string) *File

FileFromPath uploads the file at path. It is read when the request is sent.

func FileFromReader

func FileFromReader(name string, r io.Reader) *File

FileFromReader uploads what r holds, with the given file name. The reader is read once, when the request is first sent, and the bytes are reused if the request is retried.

func (*File) ContentType

func (f *File) ContentType() string

ContentType returns the content type sent with the upload.

func (*File) Name

func (f *File) Name() string

Name returns the file name sent with the upload.

func (*File) WithContentType

func (f *File) WithContentType(contentType string) *File

WithContentType sets the content type instead of detecting it from the name, and returns f.

type HTTPDoer

type HTTPDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPDoer is the part of *http.Client the SDK uses. Any *http.Client works.

type Interest

type Interest struct {
	InterestID   int64  `json:"interest_id"`
	InterestName string `json:"interest_name"`
}

Interest is a member interest that an Offer can target.

type InterestList

type InterestList struct {
	Response
	Interests []Interest `json:"interests"`
}

InterestList is the response of Interests.List.

type InterestsService

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

InterestsService lists interests.

func (*InterestsService) List

List returns the interests Offers can target (GET /interests).

type InvalidRequestError

type InvalidRequestError struct{ AgilisError }

InvalidRequestError is returned for HTTP 400 and 422, and for a refusal that arrives as HTTP 200 with a return_code starting with "E" (for example E3, when the balance is too low). StatusCode is 200 in that case.

func (*InvalidRequestError) Unwrap

func (e *InvalidRequestError) Unwrap() error

Unwrap returns the base error.

type Iter

type Iter[T any] struct {
	// contains filtered or unexported fields
}

Iter walks every item of a list, fetching the next page when the current one is used up, until has_more is false:

it := client.Offers.ListAutoPaging(ctx, nil)
for it.Next() {
	offer := it.Current()
	...
}
if err := it.Err(); err != nil { ... }

func (*Iter[T]) Current

func (it *Iter[T]) Current() T

Current returns the item Next moved to.

func (*Iter[T]) Err

func (it *Iter[T]) Err() error

Err returns the error that stopped the iteration, if any.

func (*Iter[T]) Next

func (it *Iter[T]) Next() bool

Next moves to the next item and reports whether there is one. It returns false at the end of the list or on an error; check Err afterwards.

func (*Iter[T]) Pages

func (it *Iter[T]) Pages() int

Pages returns how many pages have been fetched so far.

type LatLng

type LatLng struct {
	Latitude  float64
	Longitude float64
}

LatLng is a position: latitude first, then longitude. In JSON it is the array [latitude, longitude]; in a multipart form it is two location[] parts.

func (LatLng) MarshalJSON

func (l LatLng) MarshalJSON() ([]byte, error)

MarshalJSON encodes the position as [latitude, longitude].

type ListEventsParams

type ListEventsParams struct {
	// Environment is filled in from the key when empty.
	Environment Environment

	// Limit is the page size.
	Limit int

	// Cursor is the next_cursor of the previous page.
	Cursor string

	// EventStatus is upcoming, scheduled, rescheduled, cancelled or ended.
	EventStatus string

	// OwnerUserID lists only the Events of this user.
	OwnerUserID int64

	// CreatedAfter and CreatedBefore are ISO 8601, UTC.
	CreatedAfter  string
	CreatedBefore string
}

ListEventsParams are the parameters of Events.List. All are optional.

type ListOffersParams

type ListOffersParams struct {
	// Environment is filled in from the key when empty.
	Environment Environment

	// Limit is the page size: default 20, at most 100.
	Limit int

	// Cursor is the next_cursor of the previous page.
	Cursor string

	// OfferStatus is awaiting_payment, active, paused or ended.
	OfferStatus string

	// CreatedAfter and CreatedBefore are ISO 8601, UTC.
	CreatedAfter  string
	CreatedBefore string
}

ListOffersParams are the parameters of Offers.List. All are optional.

type ListWebhookEventsParams

type ListWebhookEventsParams struct {
	// Type lists only events of this type.
	Type string

	// DeliverySuccess false lists only events not yet delivered to every
	// endpoint; true only events delivered everywhere.
	DeliverySuccess *bool

	// Limit is the page size, 1 to 100.
	Limit int

	// Cursor is the next_cursor of the previous page.
	Cursor string
}

ListWebhookEventsParams are the parameters of WebhookEvents.List. All are optional.

type Mode

type Mode string

Mode is the mode an API key works in.

const (
	ModeTest    Mode = "test"
	ModeLive    Mode = "live"
	ModeUnknown Mode = ""
)

The modes an API key can have.

func ModeFromKey

func ModeFromKey(apiKey string) Mode

ModeFromKey returns the mode of an API key from its prefix.

func (Mode) Environment

func (m Mode) Environment() Environment

Environment returns the environment value the API uses for this mode, or "" when the mode is unknown.

type NotFoundError

type NotFoundError struct{ AgilisError }

NotFoundError is returned for HTTP 404.

func (*NotFoundError) Unwrap

func (e *NotFoundError) Unwrap() error

Unwrap returns the base error.

type Offer

type Offer struct {
	OfferID                 int64      `json:"offer_id"`
	Title                   string     `json:"title"`
	Category                string     `json:"category"`
	Description             string     `json:"description"`
	TermsAndConditions      *string    `json:"terms_and_conditions"`
	AdvertisedName          *string    `json:"advertised_name"`
	PushNotificationTitle   *string    `json:"push_notification_title"`
	PushNotificationMessage *string    `json:"push_notification_message"`
	ButtonPreset            string     `json:"button_preset"`
	ButtonText              *string    `json:"button_text"`
	URL                     string     `json:"url"`
	Image                   string     `json:"image"`
	Latitude                float64    `json:"latitude"`
	Longitude               float64    `json:"longitude"`
	Radius                  float64    `json:"radius"`
	Gender                  []string   `json:"gender"`
	Interests               []Interest `json:"interests"`
	StartDatetime           string     `json:"start_datetime"`
	ExpiryDatetime          string     `json:"expiry_datetime"`
	CreationDatetime        string     `json:"creation_datetime"`

	// OfferStatus is Awaiting Payment, Active, Scheduled, Paused or Ended.
	OfferStatus string `json:"offer_status"`

	// Status is enabled or disabled.
	Status string `json:"status"`
}

Offer is an Offer as the list returns it.

type OfferAnalytics

type OfferAnalytics struct {
	Response
	OfferID       int64        `json:"offer_id"`
	Interval      string       `json:"interval"`
	StartDatetime string       `json:"start_datetime"`
	EndDatetime   string       `json:"end_datetime"`
	Status        string       `json:"status"`
	Metrics       OfferMetrics `json:"metrics"`
}

OfferAnalytics is the response of Offers.Analytics.

type OfferList

type OfferList struct {
	Response
	Data       []Offer    `json:"data"`
	Pagination Pagination `json:"pagination"`
}

OfferList is one page of Offers.

type OfferMetrics

type OfferMetrics struct {
	Views  int64 `json:"views"`
	Clicks int64 `json:"clicks"`
}

OfferMetrics are an Offer's figures.

type OfferPriceEstimate

type OfferPriceEstimate struct {
	Response
	ReturnCode         string   `json:"return_code"`
	PriceEstimate      float64  `json:"price_estimate"`
	MatchingUsers      int64    `json:"matching_users"`
	AdUnits            int64    `json:"ad_units"`
	AdUnitPrice        float64  `json:"ad_unit_price"`
	EstimatedCost      float64  `json:"estimated_cost"`
	Currency           string   `json:"currency"`
	ExchangeRatePerGBP *float64 `json:"exchange_rate_per_gbp"`
	ExchangeRateDate   *string  `json:"exchange_rate_date"`
}

OfferPriceEstimate is the response of Offers.EstimatePrice.

type OffersService

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

OffersService creates and manages Offers.

func (*OffersService) Analytics

func (s *OffersService) Analytics(ctx context.Context, offerID int64, params *AnalyticsParams) (*OfferAnalytics, error)

Analytics returns an Offer's figures over an interval (GET /offers/{offer_id}/analytics).

func (*OffersService) Create

func (s *OffersService) Create(ctx context.Context, params *CreateOfferParams) (*CreatedOffer, error)

Create creates an Offer (POST /offers), sent as multipart/form-data with its image.

func (*OffersService) Delete

func (s *OffersService) Delete(ctx context.Context, offerID int64, params *DeleteParams) (*ActionResult, error)

Delete deletes an Offer (DELETE /offers/{offer_id}). A dry run's refund is reachable with Field("refund"). params may be nil.

func (*OffersService) EstimatePrice

EstimatePrice estimates what an Offer would cost (POST /offers/price-estimate). The environment is filled in from the key when left empty.

func (*OffersService) List

func (s *OffersService) List(ctx context.Context, params *ListOffersParams) (*OfferList, error)

List returns one page of Offers, newest first (GET /offers).

func (*OffersService) ListAutoPaging

func (s *OffersService) ListAutoPaging(ctx context.Context, params *ListOffersParams) *Iter[Offer]

ListAutoPaging returns an iterator over every Offer, following next_cursor until has_more is false.

func (*OffersService) Pause

func (s *OffersService) Pause(ctx context.Context, offerID int64) (*ActionResult, error)

Pause pauses an Offer (POST /offers/{offer_id}/pause).

func (*OffersService) Resume

func (s *OffersService) Resume(ctx context.Context, offerID int64) (*ActionResult, error)

Resume resumes a paused Offer (POST /offers/{offer_id}/resume). Its return_code is S2.

type Option

type Option func(*Client)

Option configures a Client.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets the API address. The default is DefaultBaseURL.

func WithHTTPClient

func WithHTTPClient(hc HTTPDoer) Option

WithHTTPClient sets the HTTP client used to send requests. The default is a new *http.Client.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets how many times a failed request is retried. The default is DefaultMaxRetries. Zero turns retries off.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets how long a single attempt may take. The default is DefaultTimeout. Zero or less means no timeout beyond the context's own.

type Pagination

type Pagination struct {
	Limit      int     `json:"limit"`
	Count      int     `json:"count"`
	HasMore    bool    `json:"has_more"`
	NextCursor *string `json:"next_cursor"`
}

Pagination is the pagination block of a list response.

type PermissionError

type PermissionError struct{ AgilisError }

PermissionError is returned for HTTP 403, for example when the environment is not the key's own mode.

func (*PermissionError) Unwrap

func (e *PermissionError) Unwrap() error

Unwrap returns the base error.

type PreviewEventParams

type PreviewEventParams struct {
	Title          string
	Description    string
	VenueName      string
	Address        string
	City           string
	CountryCode    string
	Location       *LatLng
	StartsAt       string
	EndsAt         string
	URL            string
	AdvertisedName *string
	PriceMin       *float64
	PriceMax       *float64
	Currency       string
	Image          *File
	Crop           *Crop
	PaymentMethod  string
	Environment    Environment
}

PreviewEventParams are the parameters of Events.Preview. Every field is optional except the environment, which is filled in from the key when empty.

type PublishEventParams

type PublishEventParams struct {
	Title       string
	Description string
	VenueName   string
	Address     string
	City        string

	// CountryCode is ISO 3166-1 alpha-2, for example GB.
	CountryCode string
	Location    LatLng

	// StartsAt and EndsAt are ISO 8601, UTC.
	StartsAt string
	EndsAt   string

	// URL is your own booking page.
	URL            string
	AdvertisedName *string

	// PriceMin, PriceMax and Currency are the ticket price. Omit all three to
	// show no price; send 0 for both to mark the event as free.
	PriceMin      *float64
	PriceMax      *float64
	Currency      string
	Image         *File
	PreviewToken  string
	SourceEventID *int64
	Crop          *Crop

	// PaymentMethod defaults to PaymentMethodBalance, the only one Events take.
	PaymentMethod string

	// Environment is filled in from the key when empty.
	Environment Environment

	// IdempotencyKey is generated (a UUID v4) when empty, and reused on
	// every retry of the call.
	IdempotencyKey string

	// DryRun checks everything and answers with the cost, creating nothing.
	DryRun bool
}

PublishEventParams are the parameters of Events.Publish. Give one image source: Image, PreviewToken or SourceEventID.

type PublishedEvent

type PublishedEvent struct {
	Response
	ReturnCode    string           `json:"return_code"`
	EventID       int64            `json:"event_id"`
	Status        string           `json:"status"`
	PaymentURL    *string          `json:"payment_url"`
	AmountCharged float64          `json:"amount_charged"`
	Currency      string           `json:"currency"`
	Category      EventCategoryRef `json:"category"`
	DryRun        bool             `json:"dry_run"`

	// IdempotencyKey is the key that was sent.
	IdempotencyKey string `json:"-"`
}

PublishedEvent is the response of Events.Publish. A dry run's listing_fee, amount_to_charge and balance_after are reachable with Field.

type RateLimitError

type RateLimitError struct {
	AgilisError

	// RetryAfter is the wait the API asked for, or 0 when it gave none.
	RetryAfter time.Duration
}

RateLimitError is returned for HTTP 429 once the retries are used up.

func (*RateLimitError) Unwrap

func (e *RateLimitError) Unwrap() error

Unwrap returns the base error.

type RescheduleEventParams

type RescheduleEventParams struct {
	// StartsAt and EndsAt are ISO 8601, UTC.
	StartsAt string `json:"starts_at"`
	EndsAt   string `json:"ends_at"`
}

RescheduleEventParams are the parameters of Events.Reschedule.

type RescheduledEvent

type RescheduledEvent struct {
	Response
	ReturnCode string `json:"return_code"`
	Message    string `json:"message"`
	EventID    int64  `json:"event_id"`
	Status     string `json:"status"`
	StartsAt   string `json:"starts_at"`
	EndsAt     string `json:"ends_at"`
}

RescheduledEvent is the response of Events.Reschedule.

type ResendWebhookEventParams

type ResendWebhookEventParams struct {
	// EndpointID sends to this endpoint only. Empty sends to every endpoint
	// the event went to.
	EndpointID string `json:"endpoint_id,omitempty"`
}

ResendWebhookEventParams are the optional parameters of WebhookEvents.Resend.

type ResentWebhookEvent

type ResentWebhookEvent struct {
	Response
	ReturnCode     string            `json:"return_code"`
	WebhookEventID string            `json:"webhook_event_id"`
	Deliveries     []WebhookDelivery `json:"deliveries"`
}

ResentWebhookEvent is the response of WebhookEvents.Resend.

type Response

type Response struct {
	// StatusCode is the HTTP status.
	StatusCode int `json:"-"`

	// Header holds the response headers.
	Header http.Header `json:"-"`

	// RawJSON is the response body as received.
	RawJSON json.RawMessage `json:"-"`
}

Response holds the HTTP details of a response. Every response type embeds it, so the status, the headers (for example X-RateLimit-Remaining) and the raw JSON, including any fields this version of the SDK does not know, stay reachable.

func (*Response) Field

func (r *Response) Field(name string) json.RawMessage

Field returns the raw JSON of a top-level field of the response, or nil when it is absent. Use it for fields this version of the SDK does not type.

func (*Response) RateLimitRemaining

func (r *Response) RateLimitRemaining() int

RateLimitRemaining returns the X-RateLimit-Remaining header, or -1 when it is absent.

type RollWebhookSecretParams

type RollWebhookSecretParams struct {
	// ExpiresIn is how long the old secret keeps signing: now, 1h, 24h or 7d.
	ExpiresIn string `json:"expires_in,omitempty"`
}

RollWebhookSecretParams are the optional parameters of WebhookEndpoints.RollSecret.

type SendTestWebhookParams

type SendTestWebhookParams struct {
	// Type is the event type to send.
	Type string `json:"type,omitempty"`
}

SendTestWebhookParams are the optional parameters of WebhookEndpoints.SendTest.

type SignatureVerificationError

type SignatureVerificationError struct {
	AgilisError

	// Reason is "header" (the signature header is missing or malformed),
	// "timestamp" (outside the tolerance) or "signature" (no v1 matches).
	Reason string
}

SignatureVerificationError is returned by ConstructEvent when a webhook message cannot be verified.

func (*SignatureVerificationError) Unwrap

func (e *SignatureVerificationError) Unwrap() error

Unwrap returns the base error.

type TestWebhookResult

type TestWebhookResult struct {
	Response
	ReturnCode     string           `json:"return_code"`
	WebhookEventID string           `json:"webhook_event_id"`
	Type           string           `json:"type"`
	Test           bool             `json:"test"`
	Delivery       *WebhookDelivery `json:"delivery"`
}

TestWebhookResult is the response of WebhookEndpoints.SendTest.

type UpdateWebhookEndpointParams

type UpdateWebhookEndpointParams struct {
	URL           *string  `json:"url,omitempty"`
	EnabledEvents []string `json:"enabled_events,omitempty"`
	Description   *string  `json:"description,omitempty"`

	// Status is enabled or disabled.
	Status *string `json:"status,omitempty"`
}

UpdateWebhookEndpointParams are the parameters of WebhookEndpoints.Update. Set only the fields to change.

type WebhookDelivery

type WebhookDelivery struct {
	EndpointID     string  `json:"endpoint_id"`
	Status         string  `json:"status"`
	Attempts       int     `json:"attempts"`
	LastHTTPStatus *int    `json:"last_http_status"`
	LastError      *string `json:"last_error"`
	NextAttemptAt  *string `json:"next_attempt_at"`
	DeliveredAt    *string `json:"delivered_at"`
}

WebhookDelivery is the delivery of a webhook event to one endpoint.

type WebhookEndpoint

type WebhookEndpoint struct {
	Response
	ReturnCode              string   `json:"return_code,omitempty"`
	ID                      string   `json:"id"`
	URL                     string   `json:"url"`
	Description             *string  `json:"description"`
	EnabledEvents           []string `json:"enabled_events"`
	Status                  string   `json:"status"`
	Livemode                bool     `json:"livemode"`
	Created                 string   `json:"created"`
	LastSuccessAt           *string  `json:"last_success_at"`
	FailingSince            *string  `json:"failing_since"`
	DisabledBy              *string  `json:"disabled_by"`
	DisabledReason          *string  `json:"disabled_reason"`
	PreviousSecretExpiresAt *string  `json:"previous_secret_expires_at"`

	// Secret is set only when the endpoint is created and when its secret is
	// rolled. Store it: it is not shown again.
	Secret string `json:"secret,omitempty"`
}

WebhookEndpoint is a webhook endpoint.

type WebhookEndpointList

type WebhookEndpointList struct {
	Response
	ReturnCode string            `json:"return_code"`
	Data       []WebhookEndpoint `json:"data"`
}

WebhookEndpointList is the response of WebhookEndpoints.List.

type WebhookEndpointsService

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

WebhookEndpointsService manages webhook endpoints.

func (*WebhookEndpointsService) Create

Create adds a webhook endpoint (POST /webhook-endpoints). The response holds the signing secret, once.

func (*WebhookEndpointsService) Delete

Delete deletes a webhook endpoint (DELETE /webhook-endpoints/{endpoint_id}).

func (*WebhookEndpointsService) Get

func (s *WebhookEndpointsService) Get(ctx context.Context, endpointID string) (*WebhookEndpoint, error)

Get returns one webhook endpoint (GET /webhook-endpoints/{endpoint_id}).

func (*WebhookEndpointsService) List

List returns the webhook endpoints of the key's mode (GET /webhook-endpoints).

func (*WebhookEndpointsService) RollSecret

func (s *WebhookEndpointsService) RollSecret(ctx context.Context, endpointID string, params *RollWebhookSecretParams) (*WebhookEndpoint, error)

RollSecret replaces an endpoint's signing secret (POST /webhook-endpoints/{endpoint_id}/roll-secret). The new secret is in the response, once. params may be nil.

func (*WebhookEndpointsService) SendTest

SendTest sends a test event to an endpoint (POST /webhook-endpoints/{endpoint_id}/test). params may be nil.

func (*WebhookEndpointsService) Update

Update changes a webhook endpoint (PATCH /webhook-endpoints/{endpoint_id}).

type WebhookEvent

type WebhookEvent struct {
	Response
	ReturnCode string `json:"return_code,omitempty"`

	// ID is the event id (whevt_...). Use it to ignore repeats.
	ID     string `json:"id"`
	Object string `json:"object,omitempty"`

	// Type is the event type, one of the EventType constants.
	Type string `json:"type"`

	// Created is when the event happened, in Unix seconds.
	Created  int64               `json:"created"`
	Livemode bool                `json:"livemode"`
	Version  int                 `json:"version,omitempty"`
	Test     bool                `json:"test"`
	Data     WebhookEventData    `json:"data"`
	Request  WebhookEventRequest `json:"request"`

	// Deliveries is set by WebhookEvents.Get and List.
	Deliveries []WebhookDelivery `json:"deliveries,omitempty"`
}

WebhookEvent is a webhook event: what ConstructEvent returns for a received message, and what WebhookEvents.Get and List return.

func ConstructEvent

func ConstructEvent(payload []byte, header, secret string, opts ...WebhookOption) (*WebhookEvent, error)

ConstructEvent verifies a received webhook message and returns its event.

payload is the request body exactly as received, header the value of the Agilis-Signature header and secret the endpoint's signing secret (whsec_...). The signature is the hex HMAC-SHA256 of "<t>.<payload>"; any matching v1 is accepted (there are two while a secret is being rolled), compared in constant time, and the timestamp must be within the tolerance.

It returns a *SignatureVerificationError when the message cannot be verified.

type WebhookEventData

type WebhookEventData struct {
	// Object is the raw JSON of data.object. Decode it with Offer, Event or
	// DecodeObject.
	Object json.RawMessage

	// Fields holds every field of data, including object, as raw JSON. Extra
	// facts such as amount_charged are here.
	Fields map[string]json.RawMessage
}

WebhookEventData is the data of a webhook event: the object (the Offer, Event or invoice, as the API returns it elsewhere) and any extra facts.

func (*WebhookEventData) DecodeObject

func (d *WebhookEventData) DecodeObject(v any) error

DecodeObject decodes data.object into v.

func (*WebhookEventData) Event

func (d *WebhookEventData) Event() (*Event, error)

Event decodes data.object as an Event, for event.* events.

func (WebhookEventData) MarshalJSON

func (d WebhookEventData) MarshalJSON() ([]byte, error)

MarshalJSON writes the data back as received.

func (*WebhookEventData) Offer

func (d *WebhookEventData) Offer() (*Offer, error)

Offer decodes data.object as an Offer, for offer.* events.

func (*WebhookEventData) UnmarshalJSON

func (d *WebhookEventData) UnmarshalJSON(b []byte) error

UnmarshalJSON keeps every field of data.

type WebhookEventList

type WebhookEventList struct {
	Response
	ReturnCode string         `json:"return_code"`
	Data       []WebhookEvent `json:"data"`
	Pagination Pagination     `json:"pagination"`
}

WebhookEventList is one page of webhook events.

type WebhookEventRequest

type WebhookEventRequest struct {
	// Source is api, mcp, ad_portal, agilis or system.
	Source         string  `json:"source"`
	IdempotencyKey *string `json:"idempotency_key"`
}

WebhookEventRequest says where the change behind a webhook event came from.

type WebhookEventsService

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

WebhookEventsService lists and resends webhook events.

func (*WebhookEventsService) Get

func (s *WebhookEventsService) Get(ctx context.Context, webhookEventID string) (*WebhookEvent, error)

Get returns one webhook event with its deliveries (GET /webhook-events/{webhook_event_id}).

func (*WebhookEventsService) List

List returns one page of the webhook events of the last 30 days, newest first (GET /webhook-events).

func (*WebhookEventsService) ListAutoPaging

ListAutoPaging returns an iterator over every webhook event, following next_cursor until has_more is false.

func (*WebhookEventsService) Resend

func (s *WebhookEventsService) Resend(ctx context.Context, webhookEventID string, params *ResendWebhookEventParams) (*ResentWebhookEvent, error)

Resend sends a webhook event again now (POST /webhook-events/{webhook_event_id}/resend). params may be nil.

type WebhookOption

type WebhookOption func(*webhookConfig)

WebhookOption configures ConstructEvent.

func WithNow

func WithNow(now func() time.Time) WebhookOption

WithNow sets the clock used for the timestamp check.

func WithTolerance

func WithTolerance(d time.Duration) WebhookOption

WithTolerance sets how far the signature's timestamp may be from now. The default is DefaultTolerance. Zero or less turns the timestamp check off.

Directories

Path Synopsis
examples
testmode command
Command testmode lists your categories and Offers with a Test key, then estimates a price and sends an Offer create as a dry run.
Command testmode lists your categories and Offers with a Test key, then estimates a price and sends an Offer create as a dry run.
webhook command
Command webhook is a minimal webhook receiver.
Command webhook is a minimal webhook receiver.

Jump to

Keyboard shortcuts

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