Help us shape the future of Go! Take the 2026 Go Developer Survey

adsefid

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 15 Imported by: 0

README

adsefid.com SMS Web Service — Go SDK

CI Go Reference

A Go client SDK for the adsefid.com SMS Web Service REST API: send single, bulk, P2P, and templated SMS and Messenger messages; check delivery status; cancel eligible unrefunded messages; fetch inbound SMS; look up account info, lines, profiles, and templates; and verify inbound webhook deliveries.

Equivalent SDKs for the same API exist for .NET, JavaScript, PHP, and Python. This SDK's public surface is structurally parallel to those, translated idiomatically to Go — see AGENTS.md for the specific, deliberate deviations.

Requirements

Go 1.22 or later. Zero third-party dependencies — this module only uses the Go standard library.

Install

go get github.com/adsefid/sdk-go

Quickstart

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	adsefid "github.com/adsefid/sdk-go"
)

func main() {
	client, err := adsefid.NewClient(os.Getenv("ADSEFID_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}

	resp, err := client.SMS.SendSingle(context.Background(), &adsefid.SendSingleSmsRequest{
		Receptor:   "09120000000",
		LineNumber: "3000000000",
		Message:    "Hello from adsefid.com!",
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("sent message %s, status=%s\n", resp.MessageID, resp.Status)
}

See examples/quickstart for a fuller version with error triage, and examples/webhookserver for a working webhook receiver.

Authentication

Every request is authenticated with a single X-API-KEY header, set from the API key you pass to NewClient. Keep it out of source control — the examples read it from an environment variable:

export ADSEFID_API_KEY="your-api-key"
client, err := adsefid.NewClient(os.Getenv("ADSEFID_API_KEY"))

NewClient returns a *adsefid.ValidationError if the key is blank.

Configuration

NewClient takes functional options:

client, err := adsefid.NewClient(
	apiKey,
	adsefid.WithBaseURL("https://api.adsefid.com"), // default; override for testing
	adsefid.WithTimeout(15 * time.Second),          // only used when WithHTTPClient is not set
	adsefid.WithUserAgent("my-service/1.0.0"),      // defaults to adsefid-go/<SDK_VERSION>
)
  • WithBaseURL(string) — overrides the default API base URL (https://api.adsefid.com).
  • WithHTTPClient(*http.Client) — supplies your own *http.Client, e.g. to install a custom http.RoundTripper for logging or a corporate proxy. Takes precedence over WithTimeout if both are set.
  • WithTimeout(time.Duration) — sets the timeout of the default *http.Client this package builds internally. Has no effect if WithHTTPClient is also supplied.
  • WithUserAgent(string) — replaces the default adsefid-go/<SDK_VERSION> User-Agent value.

Monetary response fields (Cost, TotalCost, and CreditLeft) use float64 and may contain fractional values.

Resource reference

Resource SDK method HTTP endpoint Notes
client.SMS SendSingle(ctx, *SendSingleSmsRequest) POST /v1/sms/single
client.SMS SendBulk(ctx, *SendBulkSmsRequest) POST /v1/sms/bulk Partial success is a normal typed return
client.SMS SendP2P(ctx, *SendP2PSmsRequest) POST /v1/sms/p2p Partial success is a normal typed return
client.SMS SendTemplate(ctx, *SendTemplateSmsRequest) POST /v1/sms/template
client.SMS GetStatus(ctx, *GetSmsStatusRequest) GET /v1/sms/status
client.SMS Cancel(ctx, *CancelSmsRequest) POST /v1/sms/cancel Awaiting approval, queued, or scheduled; no refund; max 2,000 distinct IDs combined
client.SMS GetReceived(ctx, *GetReceivedSmsRequest) GET /v1/sms/receive
client.Messenger SendSingle(ctx, *SendSingleMessengerRequest) POST /v1/messenger/single
client.Messenger SendBulk(ctx, *SendBulkMessengerRequest) POST /v1/messenger/bulk Partial success is a normal typed return
client.Messenger SendP2P(ctx, *SendP2PMessengerRequest) POST /v1/messenger/p2p Partial success is a normal typed return
client.Messenger UploadFile(ctx, io.Reader, fileName, contentType string) POST /v1/messenger/file Caller owns the reader
client.Messenger Cancel(ctx, *CancelMessengerRequest) POST /v1/messenger/cancel Awaiting approval, queued, or scheduled; no refund; max 2,000 distinct IDs combined
client.Messenger SendTemplate(ctx, *SendTemplateMessengerRequest) POST /v1/messenger/template
client.Messenger GetStatus(ctx, *GetMessengerStatusRequest) GET /v1/messenger/status
client.User GetInfo(ctx) GET /v1/user/info
client.User GetLines(ctx) GET /v1/user/lines
client.User GetProfiles(ctx) GET /v1/user/profiles
client.User GetTemplates(ctx, *GetUserTemplatesRequest) GET /v1/user/templates nil lists the first page in every state

Every method takes a context.Context as its first argument and returns (T, error) or (*T, error) — there are no panics for expected failure conditions. Bulk/P2P item values are sent unchanged so the API can accept or reject them independently; only request-level fields are prevalidated.

Error handling

This SDK never panics for expected failures. It defines four error types, all implementing error, and you distinguish them with errors.As:

  • *adsefid.ValidationError — a client-side pre-flight check failed (bad input shape, a message too long, a malformed local_id, etc.). No network call was made.
  • *adsefid.APIError — the API returned a non-success envelope, or a non-2xx HTTP status. Carries Code adsefid.WebServiceResponseCode, Name string, HTTPStatusCode int, and optional typed Details *adsefid.APIErrorDetails.
  • *adsefid.RateLimitError — embeds *adsefid.APIError for the rate-limit-shaped failures (WebServiceResponseCode 2035 MessageLimitReached, 2036 RequestLimitReached, or a bare HTTP 429). It unwraps to the embedded *APIError, so errors.As also matches that. adsefid.IsRateLimitError(err) is a convenience wrapper around the same check.
  • *adsefid.TransportError — a network-level failure: connection error, timeout, or a response body that could not be decoded. Wraps the underlying error (Unwrap()).

A worked example, checking the more specific *RateLimitError before the *APIError it embeds:

resp, err := client.SMS.SendSingle(ctx, req)
if err != nil {
	var valErr *adsefid.ValidationError
	if errors.As(err, &valErr) {
		log.Fatalf("bad request: %s", valErr)
	}

	var rlErr *adsefid.RateLimitError
	if errors.As(err, &rlErr) {
		log.Fatalf("rate limited (%s)", rlErr.Name)
	}

	var apiErr *adsefid.APIError
	if errors.As(err, &apiErr) {
		log.Fatalf("API error %s (code %d, HTTP %d)", apiErr.Name, int(apiErr.Code), apiErr.HTTPStatusCode)
	}

	var transportErr *adsefid.TransportError
	if errors.As(err, &transportErr) {
		log.Fatalf("transport error: %v", transportErr)
	}

	log.Fatalf("unexpected error: %v", err)
}

APIError.Details contains optional Errors map[string]APIFieldError for field errors (and rejected cancel IDs), plus optional Items []APIItemError for indexed bulk/P2P errors. Named integer codes preserve unknown future values.

Rate limits

Codes 2035, 2036, and bare HTTP 429 responses surface as *adsefid.RateLimitError.

Enums

All documented enums are typed Go constants implementing fmt.Stringer. Unrecognized wire values degrade gracefully (e.g. WebServiceResponseCode(9999)) rather than failing to parse:

  • LineSelector (int, 0-5): LineSelectorPromotionalSendBased, LineSelectorPromotionalDeliverBased, LineSelectorBulkServiceSendBased, LineSelectorBulkServiceDeliverBased, LineSelectorCustomerClubServiceSendBased, LineSelectorCustomerClubServiceDeliverBased.
  • WebServiceMessageStatus (int, 1000-1999): the status of a single message — e.g. WebServiceMessageStatusDelivered, WebServiceMessageStatusBlacklisted, WebServiceMessageStatusUnknown. See enums.go for the full set of 18 values.
  • WebServiceResponseCode (int, 2000-2047): the API's error codes — e.g. WebServiceResponseCodeInvalidAPIKey, WebServiceResponseCodeNotEnoughCredit, WebServiceResponseCodeMessageLimitReached, WebServiceResponseCodeInvalidMessageIDs, and WebServiceResponseCodeFileTooLarge. See enums.go for the full set of 48 values.
  • TemplateState (string): TemplateStatePendingApproval, TemplateStateApproved, TemplateStateRejected.
  • TemplateParameterType (string): TemplateParameterTypeString, TemplateParameterTypeNumber. The documented public set is exactly these two; the live API has been observed to also emit an undocumented third value for some templates, which this SDK intentionally does not model (see AGENTS.md).

Bulk and P2P per-item results (BulkSmsReceptorResult.Status, P2PSmsMessageResult.Status, BulkMessengerReceptorResult.Status, P2PMessengerReceptorResult.Status) are a plain int, not a typed enum, because a failed item's status can carry either a WebServiceMessageStatus (1000+) or a WebServiceResponseCode (2000+). Each item's MessageStatus() and ErrorCode() methods split that value into the typed enum for its range (ok is false for the other range and for a code this SDK does not know yet), and adsefid.MessageStatusOf/adsefid.ErrorCodeOf do the same for any raw value:

for _, item := range resp.Receptors {
	if code, ok := item.ErrorCode(); ok {
		fmt.Printf("%s: rejected (%s)\n", item.Receptor, code)
		continue
	}
	status, _ := item.MessageStatus()
	fmt.Printf("%s: %s\n", item.Receptor, status)
}

Top-level statuses (single send, get-status, cancel) are always in the 1000-1999 range and use the typed WebServiceMessageStatus.

TemplateParameterValue models a template parameter's value, which the API accepts and returns as either a JSON string or a JSON number:

params := map[string]adsefid.TemplateParameterValue{
	"name":  adsefid.StringParam("Ali"),
	"count": adsefid.IntParam(3),
	"price": adsefid.NumberParam(19.99),
}

if s, ok := params["name"].StringValue(); ok {
	fmt.Println(s)
}
Numbers, leading zeros and decimals

A parameter the template declares as number may be sent either as a JSON number or as a JSON string. The service substitutes a numeric string verbatim, so a string is the only way to keep a value's exact digits:

params := map[string]adsefid.TemplateParameterValue{
	"invoice": adsefid.StringParam("001234"), // renders as 001234, not 1234
	"amount":  adsefid.StringParam("1.50"),   // renders as 1.50, not 1.5
	"count":   adsefid.IntParam(2),           // an ordinary integer
	"rate":    adsefid.NumberParam(19.99),    // a decimal, where float rounding is acceptable
}

Use StringParam whenever the rendered text must match the digits you supplied — invoice numbers, account numbers, zero-padded codes, and money amounts with a fixed number of decimal places. NumberParam takes a float64 and therefore cannot represent every decimal exactly.

On the way back, RawNumber() returns a number as its exact wire text, while NumberValue() converts to float64:

value := resp.Parameters["amount"]
if raw, ok := value.RawNumber(); ok {
	fmt.Println(raw) // "1.50" — the trailing zero survives
}

See examples/templates for a runnable version.

File upload example

f, err := os.Open("banner.png")
if err != nil {
	log.Fatal(err)
}
defer f.Close()

uploaded, err := client.Messenger.UploadFile(ctx, f, "banner.png", "image/png")
if err != nil {
	log.Fatal(err)
}

_, err = client.Messenger.SendSingle(ctx, &adsefid.SendSingleMessengerRequest{
	Receptor: "09120000000",
	Profile:  profileID,
	Message:  "Check out our new banner!",
	FileID:   &uploaded.FileID,
})

The service enforces its documented MIME allowlist and 15 MB limit. Oversized uploads return WebServiceResponseCodeFileTooLarge (2047, HTTP 413).

Webhooks

The webhooks subpackage verifies and parses inbound webhook deliveries. It has no dependency on *adsefid.Client — a webhook receiver is typically a separate process from whatever sends messages.

Every webhook delivery carries the following headers. Use the exported constants so the wire names remain exact:

  • webhooks.HeaderID (X-Atlas-Webhook-Id) — the delivery's unique ID.
  • webhooks.HeaderSignature (X-Atlas-Webhook-Signature) — "v1=" + base64(hmac_sha256("{timestamp}.{raw_body}", secret)).
  • webhooks.HeaderTimestamp (X-Atlas-Webhook-Timestamp) — the Unix timestamp (seconds) the delivery was signed at.
  • webhooks.HeaderEvent (X-Atlas-Webhook-Event) — the event type (also present in the body as "type").
  • webhooks.HeaderAttempt (X-Atlas-Webhook-Attempt) — the 1-based delivery attempt number (also present in the body).

webhooks.Verify needs only the raw body plus the Signature and Timestamp headers — the event id, type, and attempt are also present in (and covered by the signature of) the JSON body itself.

The signing secret is Base64

Your endpoint's signing secret is shown in the adsefid.com panel as the Base64 encoding of 32 random bytes, and the service signs with those raw bytes — not with the text of the Base64 string. webhooks.Verify takes the secret exactly as the panel shows it and decodes it for you; a secret that is not valid Base64 is rejected with a *adsefid.WebhookVerificationError.

If you already hold the decoded key, use webhooks.VerifyWithKey(rawBody, signature, timestamp, key, opts...) instead and skip the decoding step.

You configure, per webhook endpoint, which event types it receives (in your adsefid.com panel) — an endpoint subscribed only to webhooks.EventTypeReceive will never see a *StatusEvent arrive, so don't assume every deployment gets all three; handle whichever ones you've subscribed to.

package main

import (
	"io"
	"log"
	"net/http"
	"os"

	"github.com/adsefid/sdk-go/webhooks"
)

func main() {
	secret := os.Getenv("ADSEFID_WEBHOOK_SECRET")

	http.HandleFunc("/webhooks/adsefid", func(w http.ResponseWriter, r *http.Request) {
		rawBody, err := io.ReadAll(r.Body)
		if err != nil {
			http.Error(w, "failed to read body", http.StatusBadRequest)
			return
		}
		defer r.Body.Close()

		signature := r.Header.Get(webhooks.HeaderSignature)
		timestamp := r.Header.Get(webhooks.HeaderTimestamp)

		event, err := webhooks.Verify(rawBody, signature, timestamp, secret)
		if err != nil {
			http.Error(w, "invalid webhook", http.StatusUnauthorized)
			return
		}

		switch e := event.(type) {
		case *webhooks.ReceiveEvent:
			for _, item := range e.Data {
				log.Printf("received SMS on %s from %s: %q", item.LineNumber, item.Sender, item.Message)
			}
		case *webhooks.StatusEvent:
			for _, item := range e.Data {
				log.Printf("SMS %s -> %s", item.ID, item.StatusDelivery)
			}
		case *webhooks.MessengerStatusEvent:
			for _, item := range e.Data {
				log.Printf("Messenger %s -> %s", item.ID, item.StatusDelivery)
			}
		}

		w.WriteHeader(http.StatusOK)
	})

	log.Fatal(http.ListenAndServe(":8080", nil))
}

See examples/webhookserver for the complete, runnable version.

webhooks.Verify accepts a webhooks.WithMaxAge(time.Duration) option to override the default 5-minute staleness window, and returns a *adsefid.WebhookVerificationError for any verification or parsing failure (bad signature, stale timestamp, malformed or unrecognized payload).

Development

make deps    # go mod download
make fmt     # gofmt + goimports
make lint    # go vet + golangci-lint
make build   # go build ./...
make test    # go test ./...

gofmt, go vet and go test ship with the Go toolchain. golangci-lint needs a one-time install:

brew install golangci-lint

The test suite uses only the standard library (testing plus net/http/httptest), so go.mod stays dependency-free. Golden fixtures live in testdata/ and are byte-identical to the same tree in the sibling SDK repositories; TestFixturesIntegrity verifies them against CHECKSUMS.txt.

Examples

Each directory under examples/ is a standalone package main. Run one with go run:

export ADSEFID_API_KEY=...
export ADSEFID_LINE_NUMBER=983000XXX

go run ./examples/account          # account info, lines, profiles, templates; client configuration
go run ./examples/quickstart       # send one SMS, with full error triage
go run ./examples/bulkandp2p       # bulk + P2P sends, and reading a partial success
go run ./examples/templates        # list templates and send one, incl. exact numeric values
go run ./examples/statusandcancel  # delivery status, cancelling, inbound messages
go run ./examples/messenger        # upload an attachment and send it via a messenger profile
go run ./examples/webhookserver    # verify and dispatch inbound webhooks

examples/account sends nothing, so it is the safest one to try first.

Versioning

This SDK follows Semantic Versioning independently of the API documentation.

  • SDK version: 0.6.0 (repository tag v0.6.0)
  • Verified API documentation: v1.14.0

SDK releases use v<SDK_VERSION> tags. The two version numbers move independently. A future major version v2 must also change the module path to github.com/adsefid/sdk-go/v2.

License

MIT — see LICENSE.

Documentation

Overview

Package adsefid is a client SDK for the adsefid.com SMS Web Service REST API.

It provides SMS, Messenger, and User resources through a single Client, and a sibling github.com/adsefid/sdk-go/webhooks package for verifying and parsing inbound webhook deliveries.

Getting started

client, err := adsefid.NewClient(os.Getenv("ADSEFID_API_KEY"))
if err != nil {
	log.Fatal(err)
}

resp, err := client.SMS.SendSingle(ctx, &adsefid.SendSingleSmsRequest{
	Receptor:   "09120000000",
	LineNumber: "3000...",
	Message:    "hello",
})

Errors

Every method returns a plain Go error. Client-side pre-flight failures (bad input, never touching the network) come back as a *ValidationError. Network or timeout problems come back as a *TransportError. A non-success API response comes back as an *APIError, or as a *RateLimitError (which wraps an *APIError) for rate-limit-shaped failures. Use errors.As to distinguish them; see the package README for a full worked example.

Deliberate deviations from the sibling SDKs

Equivalent SDKs exist for this same API in other languages (.NET, JS, PHP, Python). This package intentionally departs from their approach in a few places where the idiomatic Go choice differs:

  • JSON is handled via the standard library's reflection-based encoding/json, with `json:"snake_case"` struct tags. The other SDKs favor a "zero reflection" approach for AOT-trimming reasons that are specific to their runtimes (chiefly .NET Native AOT); that concern doesn't apply to Go, where encoding/json is the idiomatic default and hand-rolling (un)marshaling for every type would be unusual and costly for no real benefit.
  • Identifiers (group_id, message_id, profile, file_id, and webhook item ids) are plain strings, not a dedicated UUID type. The standard library has no UUID type, and importing one (e.g. google/uuid) would violate this module's zero-dependency policy.
  • Enums are permissively-typed by construction: an unrecognized integer or string value from the wire simply becomes that named Go type's value (e.g. a WebServiceResponseCode of 9999), rather than failing to parse. Go's named-integer/string type system makes this automatic, unlike the explicit "parse permissively, keep the raw value alongside" workarounds needed in more strictly-enumerated languages.

Known doc-vs-reality subtleties

See the doc comments on TemplateParameterType and on the bulk/P2P per-item result types (their Status fields are a plain int, not a typed enum) for two places where this SDK intentionally departs from a literal reading of the published API documentation to match observed live-API behavior. Both are also called out in AGENTS.md.

Index

Constants

View Source
const DefaultBaseURL = "https://api.adsefid.com"

DefaultBaseURL is the default base URL used by NewClient when WithBaseURL is not supplied.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	// Code is the API's error code. It is -1 when the HTTP status was non-2xx
	// but the response body could not be decoded as an error envelope.
	Code WebServiceResponseCode
	// Name is the SCREAMING_SNAKE error name reported by the API (e.g.
	// "INVALID_API_KEY"), or "UNKNOWN_ERROR" when Code is -1.
	Name string
	// HTTPStatusCode is the HTTP status code of the response.
	HTTPStatusCode int
	// Details carries structured field and item errors, if any.
	Details *APIErrorDetails
}

APIError reports a non-success response envelope, or a non-2xx HTTP status that could not be decoded as one, returned by the adsefid.com API.

func (*APIError) Error

func (e *APIError) Error() string

type APIErrorDetails added in v0.5.0

type APIErrorDetails struct {
	Errors map[string]APIFieldError `json:"errors,omitempty"`
	Items  []APIItemError           `json:"items,omitempty"`
}

APIErrorDetails is the structured error-details shape shared by all API endpoint families. Empty properties are omitted by the service.

type APIFieldError added in v0.5.0

type APIFieldError struct {
	Code WebServiceResponseCode `json:"code"`
	Name string                 `json:"name"`
}

APIFieldError is one field-level error in an API error envelope. Code is a named integer, so a newer server code remains readable by older SDKs.

type APIItemError added in v0.5.0

type APIItemError struct {
	Index  int                      `json:"index"`
	Errors map[string]APIFieldError `json:"errors"`
}

APIItemError contains errors for one rejected bulk or P2P request item.

type BulkMessengerReceptor

type BulkMessengerReceptor struct {
	Receptor string  `json:"receptor"`
	LocalID  *string `json:"local_id,omitempty"`
	Hide     *bool   `json:"hide,omitempty"`
}

BulkMessengerReceptor is one entry of SendBulkMessengerRequest.Receptors.

type BulkMessengerReceptorResult

type BulkMessengerReceptorResult struct {
	MessageID *string `json:"message_id"`
	Receptor  string  `json:"receptor"`
	LocalID   *string `json:"local_id"`
	Hide      bool    `json:"hide"`
	Status    int     `json:"status"`
	Cost      float64 `json:"cost"`
}

BulkMessengerReceptorResult is one entry of SendBulkMessengerResponse.Receptors.

Status is a plain int, not a typed WebServiceMessageStatus, because a failed per-receptor result can carry a WebServiceResponseCode (2000+) instead of a WebServiceMessageStatus (1000-1999).

func (BulkMessengerReceptorResult) ErrorCode added in v0.4.0

ErrorCode returns the typed error code when Status is 2000 or above and names an error this SDK knows, meaning this one item was rejected; see ErrorCodeOf.

func (BulkMessengerReceptorResult) MessageStatus added in v0.4.0

MessageStatus returns the typed message status when Status is in 1000-1999 and names a status this SDK knows; see MessageStatusOf.

type BulkSmsReceptor

type BulkSmsReceptor struct {
	Receptor string  `json:"receptor"`
	LocalID  *string `json:"local_id,omitempty"`
	Hide     *bool   `json:"hide,omitempty"`
}

BulkSmsReceptor is one entry of SendBulkSmsRequest.Receptors.

type BulkSmsReceptorResult

type BulkSmsReceptorResult struct {
	MessageID *string `json:"message_id"`
	Receptor  string  `json:"receptor"`
	LocalID   *string `json:"local_id"`
	Status    int     `json:"status"`
	Hide      bool    `json:"hide"`
	Cost      float64 `json:"cost"`
}

BulkSmsReceptorResult is one entry of SendBulkSmsResponse.Receptors.

Status is a plain int, not a typed WebServiceMessageStatus, because a failed per-receptor result can carry a WebServiceResponseCode (2000+) instead of a WebServiceMessageStatus (1000-1999). MessageStatus and ErrorCode split it into the typed enum for its range.

func (BulkSmsReceptorResult) ErrorCode added in v0.4.0

ErrorCode returns the typed error code when Status is 2000 or above and names an error this SDK knows, meaning this one item was rejected; see ErrorCodeOf.

func (BulkSmsReceptorResult) MessageStatus added in v0.4.0

func (r BulkSmsReceptorResult) MessageStatus() (WebServiceMessageStatus, bool)

MessageStatus returns the typed message status when Status is in 1000-1999 and names a status this SDK knows; see MessageStatusOf.

type CancelMessengerRequest

type CancelMessengerRequest struct {
	MessageIDs []string `json:"message_ids,omitempty"`
	LocalIDs   []string `json:"local_ids,omitempty"`
}

CancelMessengerRequest is the request body for MessengerService.Cancel. At least one of MessageIDs or LocalIDs must be non-empty.

type CancelMessengerResponse

type CancelMessengerResponse struct {
	CancelledMessages []CancelledMessengerItem `json:"cancelled_messages"`
	FailedToCancel    []CancelledMessengerItem `json:"failed_to_cancel"`
}

CancelMessengerResponse is the response body for MessengerService.Cancel.

type CancelSmsRequest

type CancelSmsRequest struct {
	MessageIDs []string `json:"message_ids,omitempty"`
	LocalIDs   []string `json:"local_ids,omitempty"`
}

CancelSmsRequest is the request body for SMSService.Cancel. At least one of MessageIDs or LocalIDs must be non-empty.

type CancelSmsResponse

type CancelSmsResponse struct {
	CancelledMessages []CancelledSmsItem `json:"cancelled_messages"`
	FailedToCancel    []CancelledSmsItem `json:"failed_to_cancel"`
}

CancelSmsResponse is the response body for SMSService.Cancel.

type CancelledMessengerItem

type CancelledMessengerItem struct {
	MessageID string                  `json:"message_id"`
	LocalID   *string                 `json:"local_id"`
	Status    WebServiceMessageStatus `json:"status"`
}

CancelledMessengerItem is one entry of CancelMessengerResponse.CancelledMessages or CancelMessengerResponse.FailedToCancel.

type CancelledSmsItem

type CancelledSmsItem struct {
	MessageID string                  `json:"message_id"`
	LocalID   *string                 `json:"local_id"`
	Status    WebServiceMessageStatus `json:"status"`
}

CancelledSmsItem is one entry of CancelSmsResponse.CancelledMessages or CancelSmsResponse.FailedToCancel.

type Client

type Client struct {
	SMS       *SMSService
	Messenger *MessengerService
	User      *UserService
	// contains filtered or unexported fields
}

Client is a client for the adsefid.com SMS Web Service API. Construct one with NewClient. A *Client is safe for concurrent use by multiple goroutines, as long as the *http.Client it holds is.

func NewClient

func NewClient(apiKey string, opts ...ClientOption) (*Client, error)

NewClient constructs a Client authenticated with apiKey, which is sent on every request as the X-API-KEY header. It returns a *ValidationError if apiKey is blank.

type ClientOption

type ClientOption func(*clientConfig)

ClientOption configures a Client constructed by NewClient.

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL overrides the default API base URL (https://api.adsefid.com). This is mainly useful for testing against a mock server.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient supplies a custom *http.Client for the SDK to use. When set, it takes precedence over WithTimeout: WithTimeout only affects the *http.Client this package builds internally when WithHTTPClient is not used.

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout sets the timeout of the default *http.Client this package builds when WithHTTPClient is not supplied. It has no effect if WithHTTPClient is also supplied.

func WithUserAgent

func WithUserAgent(userAgent string) ClientOption

WithUserAgent replaces the default adsefid-go/<SDK_VERSION> User-Agent value.

type GetMessengerStatusRequest added in v0.4.0

type GetMessengerStatusRequest struct {
	MessageIDs []string
	LocalIDs   []string
}

GetMessengerStatusRequest is the query for MessengerService.GetStatus. At least one of MessageIDs or LocalIDs must be non-empty, and their combined distinct count must not exceed 2000.

type GetMessengerStatusResponse

type GetMessengerStatusResponse struct {
	Receptors []MessengerStatusItem `json:"receptors"`
}

GetMessengerStatusResponse is the response body for MessengerService.GetStatus.

type GetReceivedSmsRequest added in v0.4.0

type GetReceivedSmsRequest struct {
	LineNumber string
	Count      *int
	Since      *time.Time
}

GetReceivedSmsRequest is the query for SMSService.GetReceived. LineNumber is required; Count (if set) must be in [1, 499]; Since (if set) filters to messages received at or after that time.

type GetReceivedSmsResponse

type GetReceivedSmsResponse struct {
	Messages []ReceivedSmsMessage `json:"messages"`
}

GetReceivedSmsResponse is the response body for SMSService.GetReceived.

type GetSmsStatusRequest added in v0.4.0

type GetSmsStatusRequest struct {
	MessageIDs []string
	LocalIDs   []string
}

GetSmsStatusRequest is the query for SMSService.GetStatus. At least one of MessageIDs or LocalIDs must be non-empty, and their combined distinct count must not exceed 2000.

type GetSmsStatusResponse

type GetSmsStatusResponse struct {
	Receptors []SmsStatusItem `json:"receptors"`
}

GetSmsStatusResponse is the response body for SMSService.GetStatus.

type GetUserTemplatesRequest added in v0.4.0

type GetUserTemplatesRequest struct {
	State *TemplateState
	Skip  *int
	Take  *int
}

GetUserTemplatesRequest is the query for UserService.GetTemplates. Every field is optional: State filters by moderation state; Skip (if set) must be non-negative; Take (if set) must be in [1, 100].

type GetUserTemplatesResponse

type GetUserTemplatesResponse struct {
	Items []UserTemplate `json:"items"`
	Total int            `json:"total"`
}

GetUserTemplatesResponse is the response body for UserService.GetTemplates.

type LineSelector

type LineSelector int

LineSelector selects which line-accounting mode a send should use. See the adsefid.com API documentation (doc v1.13.0, section 3.1).

const (
	LineSelectorPromotionalSendBased            LineSelector = 0
	LineSelectorPromotionalDeliverBased         LineSelector = 1
	LineSelectorBulkServiceSendBased            LineSelector = 2
	LineSelectorBulkServiceDeliverBased         LineSelector = 3
	LineSelectorCustomerClubServiceSendBased    LineSelector = 4
	LineSelectorCustomerClubServiceDeliverBased LineSelector = 5
)

func (LineSelector) String

func (v LineSelector) String() string

type MessengerService

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

MessengerService groups the Messenger endpoints of the adsefid.com API. Obtain one via Client.Messenger rather than constructing it directly.

func (*MessengerService) Cancel

Cancel cancels eligible messages by message ID or local ID. Requires at least one ID, with at most 2000 distinct IDs across both lists.

func (*MessengerService) GetStatus

GetStatus looks up the delivery status of previously sent messages by message ID and/or local ID.

func (*MessengerService) SendBulk

SendBulk sends the same message to many receptors in one call. Item errors are returned in the partial API response.

func (*MessengerService) SendP2P

SendP2P sends distinct, per-receptor messages in one call. Item errors are returned in the partial API response.

func (*MessengerService) SendSingle

SendSingle sends a single Messenger message to one receptor.

func (*MessengerService) SendTemplate

SendTemplate sends a pre-approved message template, filled in with Parameters, to one receptor.

func (*MessengerService) UploadFile

func (m *MessengerService) UploadFile(ctx context.Context, r io.Reader, fileName, contentType string) (*UploadMessengerFileResponse, error)

UploadFile uploads a file (image, video, or document, per the API's supported-type list) to be attached to a subsequent Messenger send via its returned FileID. r is read to completion but never closed by this method.

type MessengerStatusItem

type MessengerStatusItem struct {
	MessageID    string                  `json:"message_id"`
	LocalID      *string                 `json:"local_id"`
	Status       WebServiceMessageStatus `json:"status"`
	Receptor     string                  `json:"receptor"`
	SendTime     *time.Time              `json:"send_time"`
	DeliveryTime *time.Time              `json:"delivery_time"`
}

MessengerStatusItem is one entry of GetMessengerStatusResponse.Receptors.

type P2PMessengerReceptor

type P2PMessengerReceptor struct {
	Receptor string  `json:"receptor"`
	Message  string  `json:"message"`
	LocalID  *string `json:"local_id,omitempty"`
	Hide     *bool   `json:"hide,omitempty"`
}

P2PMessengerReceptor is one entry of SendP2PMessengerRequest.Receptors.

type P2PMessengerReceptorResult

type P2PMessengerReceptorResult struct {
	MessageID *string `json:"message_id"`
	Receptor  string  `json:"receptor"`
	Message   string  `json:"message"`
	LocalID   *string `json:"local_id"`
	Hide      bool    `json:"hide"`
	Status    int     `json:"status"`
	Cost      float64 `json:"cost"`
}

P2PMessengerReceptorResult is one entry of SendP2PMessengerResponse.Receptors.

Status is a plain int; see BulkMessengerReceptorResult.Status for why.

func (P2PMessengerReceptorResult) ErrorCode added in v0.4.0

ErrorCode returns the typed error code when Status is 2000 or above and names an error this SDK knows, meaning this one item was rejected; see ErrorCodeOf.

func (P2PMessengerReceptorResult) MessageStatus added in v0.4.0

MessageStatus returns the typed message status when Status is in 1000-1999 and names a status this SDK knows; see MessageStatusOf.

type P2PSmsMessage

type P2PSmsMessage struct {
	Receptor string  `json:"receptor"`
	Message  string  `json:"message"`
	LocalID  *string `json:"local_id,omitempty"`
	Hide     *bool   `json:"hide,omitempty"`
}

P2PSmsMessage is one entry of SendP2PSmsRequest.Messages.

type P2PSmsMessageResult

type P2PSmsMessageResult struct {
	MessageID    *string `json:"message_id"`
	Receptor     string  `json:"receptor"`
	Status       int     `json:"status"`
	LocalID      *string `json:"local_id"`
	Message      string  `json:"message"`
	Hide         bool    `json:"hide"`
	SegmentCount int     `json:"segment_count"`
	Cost         float64 `json:"cost"`
}

P2PSmsMessageResult is one entry of SendP2PSmsResponse.Messages.

Status is a plain int; see BulkSmsReceptorResult.Status for why.

func (P2PSmsMessageResult) ErrorCode added in v0.4.0

ErrorCode returns the typed error code when Status is 2000 or above and names an error this SDK knows, meaning this one item was rejected; see ErrorCodeOf.

func (P2PSmsMessageResult) MessageStatus added in v0.4.0

func (r P2PSmsMessageResult) MessageStatus() (WebServiceMessageStatus, bool)

MessageStatus returns the typed message status when Status is in 1000-1999 and names a status this SDK knows; see MessageStatusOf.

type RateLimitError

type RateLimitError struct {
	*APIError
}

RateLimitError reports an APIError whose code indicates the caller has been rate-limited (WebServiceResponseCode 2035 MessageLimitReached, 2036 RequestLimitReached, or a bare HTTP 429 with no decodable error envelope).

func IsRateLimitError

func IsRateLimitError(err error) (*RateLimitError, bool)

IsRateLimitError reports whether err is, or wraps, a *RateLimitError, and returns it if so. It is a thin convenience wrapper around errors.As.

func (*RateLimitError) Unwrap

func (e *RateLimitError) Unwrap() error

type ReceivedSmsMessage

type ReceivedSmsMessage struct {
	Message     string    `json:"message"`
	LineNumber  string    `json:"line_number"`
	ReceiveDate time.Time `json:"receive_date"`
	Sender      string    `json:"sender"`
}

ReceivedSmsMessage is one entry of GetReceivedSmsResponse.Messages.

type SMSService

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

SMSService groups the SMS endpoints of the adsefid.com API. Obtain one via Client.SMS rather than constructing it directly.

func (*SMSService) Cancel

Cancel cancels eligible messages by message ID or local ID. Requires at least one ID, with at most 2000 distinct IDs across both lists.

func (*SMSService) GetReceived

GetReceived fetches inbound SMS messages received on req.LineNumber.

func (*SMSService) GetStatus

GetStatus looks up the delivery status of previously sent messages by message ID and/or local ID.

func (*SMSService) SendBulk

SendBulk sends the same message to many receptors in one call. Item errors are returned in the partial API response.

func (*SMSService) SendP2P

SendP2P sends distinct, per-receptor messages in one call. Item errors are returned in the partial API response.

func (*SMSService) SendSingle

SendSingle sends a single SMS message to one receptor.

func (*SMSService) SendTemplate

SendTemplate sends a pre-approved message template, filled in with Parameters, to one receptor.

type SendBulkMessengerRequest

type SendBulkMessengerRequest struct {
	Receptors []BulkMessengerReceptor `json:"receptors"`
	Message   string                  `json:"message"`
	SendTime  *time.Time              `json:"send_time,omitempty"`
	Profile   string                  `json:"profile"`
	FileID    *string                 `json:"file_id,omitempty"`
}

SendBulkMessengerRequest is the request body for MessengerService.SendBulk.

type SendBulkMessengerResponse

type SendBulkMessengerResponse struct {
	GroupID    string                        `json:"group_id"`
	Receptors  []BulkMessengerReceptorResult `json:"receptors"`
	Message    string                        `json:"message"`
	SendTime   *time.Time                    `json:"send_time"`
	TotalCount int                           `json:"total_count"`
	TotalCost  float64                       `json:"total_cost"`
	Counts     map[string]int                `json:"counts"`
	Profile    string                        `json:"profile"`
	Messenger  string                        `json:"messenger"`
}

SendBulkMessengerResponse is the response body for MessengerService.SendBulk.

type SendBulkSmsRequest

type SendBulkSmsRequest struct {
	Receptors    []BulkSmsReceptor `json:"receptors"`
	Message      string            `json:"message"`
	SendTime     *time.Time        `json:"send_time,omitempty"`
	LineNumber   string            `json:"line_number"`
	LineSelector *LineSelector     `json:"line_selector,omitempty"`
}

SendBulkSmsRequest is the request body for SMSService.SendBulk.

type SendBulkSmsResponse

type SendBulkSmsResponse struct {
	GroupID      string                  `json:"group_id"`
	Receptors    []BulkSmsReceptorResult `json:"receptors"`
	Message      string                  `json:"message"`
	SegmentCount int                     `json:"segment_count"`
	SendTime     *time.Time              `json:"send_time"`
	LineNumber   string                  `json:"line_number"`
	LineSelector LineSelector            `json:"line_selector"`
	Counts       map[string]int          `json:"counts"`
	TotalCount   int                     `json:"total_count"`
	TotalCost    float64                 `json:"total_cost"`
}

SendBulkSmsResponse is the response body for SMSService.SendBulk.

type SendP2PMessengerRequest

type SendP2PMessengerRequest struct {
	Receptors []P2PMessengerReceptor `json:"receptors"`
	SendTime  *time.Time             `json:"send_time,omitempty"`
	Profile   string                 `json:"profile"`
	FileID    *string                `json:"file_id,omitempty"`
}

SendP2PMessengerRequest is the request body for MessengerService.SendP2P.

type SendP2PMessengerResponse

type SendP2PMessengerResponse struct {
	GroupID    string                       `json:"group_id"`
	Receptors  []P2PMessengerReceptorResult `json:"receptors"`
	SendTime   *time.Time                   `json:"send_time"`
	TotalCount int                          `json:"total_count"`
	TotalCost  float64                      `json:"total_cost"`
	Counts     map[string]int               `json:"counts"`
	Profile    string                       `json:"profile"`
	Messenger  string                       `json:"messenger"`
}

SendP2PMessengerResponse is the response body for MessengerService.SendP2P.

type SendP2PSmsRequest

type SendP2PSmsRequest struct {
	Messages     []P2PSmsMessage `json:"messages"`
	SendTime     *time.Time      `json:"send_time,omitempty"`
	LineNumber   string          `json:"line_number"`
	LineSelector *LineSelector   `json:"line_selector,omitempty"`
}

SendP2PSmsRequest is the request body for SMSService.SendP2P.

type SendP2PSmsResponse

type SendP2PSmsResponse struct {
	GroupID      string                `json:"group_id"`
	Messages     []P2PSmsMessageResult `json:"messages"`
	SendTime     *time.Time            `json:"send_time"`
	LineNumber   string                `json:"line_number"`
	LineSelector LineSelector          `json:"line_selector"`
	TotalCost    float64               `json:"total_cost"`
	Counts       map[string]int        `json:"counts"`
}

SendP2PSmsResponse is the response body for SMSService.SendP2P.

type SendSingleMessengerRequest

type SendSingleMessengerRequest struct {
	Message  string     `json:"message"`
	Receptor string     `json:"receptor"`
	Profile  string     `json:"profile"`
	Hide     *bool      `json:"hide,omitempty"`
	FileID   *string    `json:"file_id,omitempty"`
	SendTime *time.Time `json:"send_time,omitempty"`
	LocalID  *string    `json:"local_id,omitempty"`
}

SendSingleMessengerRequest is the request body for MessengerService.SendSingle.

type SendSingleMessengerResponse

type SendSingleMessengerResponse struct {
	GroupID   string                  `json:"group_id"`
	MessageID string                  `json:"message_id"`
	Status    WebServiceMessageStatus `json:"status"`
	Receptor  string                  `json:"receptor"`
	LocalID   *string                 `json:"local_id"`
	Hide      bool                    `json:"hide"`
	Cost      float64                 `json:"cost"`
	SendTime  *time.Time              `json:"send_time"`
	Profile   string                  `json:"profile"`
	Messenger string                  `json:"messenger"`
}

SendSingleMessengerResponse is the response body for MessengerService.SendSingle.

type SendSingleSmsRequest

type SendSingleSmsRequest struct {
	Receptor     string        `json:"receptor"`
	LineNumber   string        `json:"line_number"`
	LineSelector *LineSelector `json:"line_selector,omitempty"`
	Message      string        `json:"message"`
	SendTime     *time.Time    `json:"send_time,omitempty"`
	LocalID      *string       `json:"local_id,omitempty"`
	Hide         *bool         `json:"hide,omitempty"`
}

SendSingleSmsRequest is the request body for SMSService.SendSingle.

type SendSingleSmsResponse

type SendSingleSmsResponse struct {
	GroupID      string                  `json:"group_id"`
	LocalID      *string                 `json:"local_id"`
	Status       WebServiceMessageStatus `json:"status"`
	LineNumber   string                  `json:"line_number"`
	LineSelector LineSelector            `json:"line_selector"`
	Cost         float64                 `json:"cost"`
	Receptor     string                  `json:"receptor"`
	SendTime     *time.Time              `json:"send_time"`
	MessageID    string                  `json:"message_id"`
	SegmentCount int                     `json:"segment_count"`
	Hide         bool                    `json:"hide"`
}

SendSingleSmsResponse is the response body for SMSService.SendSingle.

type SendTemplateMessengerRequest

type SendTemplateMessengerRequest struct {
	TemplateID string                            `json:"template_id"`
	Parameters map[string]TemplateParameterValue `json:"parameters"`
	Receptor   string                            `json:"receptor"`
	LocalID    *string                           `json:"local_id,omitempty"`
	Profile    string                            `json:"profile"`
	ExpiryDate *time.Time                        `json:"expiry_date,omitempty"`
}

SendTemplateMessengerRequest is the request body for MessengerService.SendTemplate.

type SendTemplateMessengerResponse

type SendTemplateMessengerResponse struct {
	GroupID    string                            `json:"group_id"`
	MessageID  string                            `json:"message_id"`
	Status     WebServiceMessageStatus           `json:"status"`
	LocalID    *string                           `json:"local_id"`
	TemplateID string                            `json:"template_id"`
	SendTime   *time.Time                        `json:"send_time"`
	ExpiryDate *time.Time                        `json:"expiry_date"`
	Cost       float64                           `json:"cost"`
	Receptor   string                            `json:"receptor"`
	Message    string                            `json:"message"`
	Profile    string                            `json:"profile"`
	Messenger  string                            `json:"messenger"`
	Parameters map[string]TemplateParameterValue `json:"parameters"`
}

SendTemplateMessengerResponse is the response body for MessengerService.SendTemplate.

type SendTemplateSmsRequest

type SendTemplateSmsRequest struct {
	TemplateID   string                            `json:"template_id"`
	Parameters   map[string]TemplateParameterValue `json:"parameters"`
	Receptor     string                            `json:"receptor"`
	LocalID      *string                           `json:"local_id,omitempty"`
	LineNumber   string                            `json:"line_number"`
	LineSelector *LineSelector                     `json:"line_selector,omitempty"`
	ExpiryDate   *time.Time                        `json:"expiry_date,omitempty"`
}

SendTemplateSmsRequest is the request body for SMSService.SendTemplate.

type SendTemplateSmsResponse

type SendTemplateSmsResponse struct {
	GroupID      string                            `json:"group_id"`
	MessageID    string                            `json:"message_id"`
	Status       WebServiceMessageStatus           `json:"status"`
	LocalID      *string                           `json:"local_id"`
	LineNumber   string                            `json:"line_number"`
	TemplateID   string                            `json:"template_id"`
	SendTime     *time.Time                        `json:"send_time"`
	ExpiryDate   *time.Time                        `json:"expiry_date"`
	LineSelector LineSelector                      `json:"line_selector"`
	Cost         float64                           `json:"cost"`
	Receptor     string                            `json:"receptor"`
	Message      string                            `json:"message"`
	SegmentCount int                               `json:"segment_count"`
	Parameters   map[string]TemplateParameterValue `json:"parameters"`
}

SendTemplateSmsResponse is the response body for SMSService.SendTemplate.

type SmsStatusItem

type SmsStatusItem struct {
	MessageID    string                  `json:"message_id"`
	LocalID      *string                 `json:"local_id"`
	Status       WebServiceMessageStatus `json:"status"`
	Receptor     string                  `json:"receptor"`
	SendTime     *time.Time              `json:"send_time"`
	DeliveryTime *time.Time              `json:"delivery_time"`
}

SmsStatusItem is one entry of GetSmsStatusResponse.Receptors.

type TemplateParameterType

type TemplateParameterType string

TemplateParameterType is the declared type of one template parameter, as reported by GetTemplates. See doc section 3.6.

The documented, supported public set is exactly {string, number}. The live API has been observed to also emit a third, undocumented value for some templates; this SDK intentionally does not model or expose it. If you need to detect it, compare the raw wire value defensively rather than assuming it is always one of the two constants below.

const (
	TemplateParameterTypeString TemplateParameterType = "string"
	TemplateParameterTypeNumber TemplateParameterType = "number"
)

func (TemplateParameterType) String

func (v TemplateParameterType) String() string

type TemplateParameterValue

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

TemplateParameterValue is the value bound to a single named template parameter, sent when sending a templated SMS or Messenger message and received back on the response. The API accepts either a JSON string or a JSON number for a template parameter, so this type marshals and unmarshals as whichever of the two it currently holds.

For a parameter the template declares as "number", pass a string whenever the exact lexical form matters — StringParam("001234") keeps the leading zeros, and StringParam("1.50") keeps the trailing zero. The server accepts a numeric string for a number parameter and substitutes it verbatim. Numbers themselves may be decimal.

func IntParam

func IntParam(value int64) TemplateParameterValue

IntParam builds a TemplateParameterValue holding an integer.

func NumberParam

func NumberParam(value float64) TemplateParameterValue

NumberParam builds a TemplateParameterValue holding a floating-point number. Note that a float64 cannot represent every decimal exactly; use StringParam when the exact decimal form matters.

func StringParam

func StringParam(value string) TemplateParameterValue

StringParam builds a TemplateParameterValue holding a string.

func (TemplateParameterValue) IsNumber

func (v TemplateParameterValue) IsNumber() bool

IsNumber reports whether this value holds a number (as opposed to a string).

func (TemplateParameterValue) MarshalJSON

func (v TemplateParameterValue) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (TemplateParameterValue) NumberValue

func (v TemplateParameterValue) NumberValue() (float64, bool)

NumberValue returns the held number as a float64 and true, or 0 and false if this value holds a string instead. Use RawNumber to read the number without going through binary floating point.

func (TemplateParameterValue) RawNumber

func (v TemplateParameterValue) RawNumber() (json.Number, bool)

RawNumber returns the held number as its exact decimal text and true, or "" and false if this value holds a string instead. This is the lossless view: a number read off the wire round-trips through it unchanged.

func (TemplateParameterValue) StringValue

func (v TemplateParameterValue) StringValue() (string, bool)

StringValue returns the held string and true, or "" and false if this value holds a number instead.

func (*TemplateParameterValue) UnmarshalJSON

func (v *TemplateParameterValue) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler. It accepts a JSON string or a JSON number and rejects anything else. A number is retained as its exact wire text rather than being converted to float64.

type TemplateState

type TemplateState string

TemplateState is the moderation state of a user-defined message template. See doc section 3.5.

const (
	TemplateStatePendingApproval TemplateState = "pendingapproval"
	TemplateStateApproved        TemplateState = "approved"
	TemplateStateRejected        TemplateState = "rejected"
)

func (TemplateState) String

func (v TemplateState) String() string

type TransportError

type TransportError struct {
	Message string
	Err     error
}

TransportError reports a network-level failure (connection error, timeout, response body/JSON that could not be decoded) that occurred while talking to the adsefid.com API.

func (*TransportError) Error

func (e *TransportError) Error() string

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

type UploadMessengerFileResponse

type UploadMessengerFileResponse struct {
	FileID string `json:"file_id"`
}

UploadMessengerFileResponse is the response body for MessengerService.UploadFile.

type UserInfo

type UserInfo struct {
	Name          string  `json:"name"`
	CompanyName   *string `json:"company_name"`
	CreditLeft    float64 `json:"credit_left"`
	Email         *string `json:"email"`
	Phone         *string `json:"phone"`
	AccountStatus string  `json:"account_status"`
}

UserInfo is the response body for UserService.GetInfo.

type UserLine

type UserLine struct {
	LineNumber   string       `json:"line_number"`
	LineSelector LineSelector `json:"line_selector"`
	LineName     string       `json:"line_name"`
	Enabled      bool         `json:"enabled"`
}

UserLine is one entry of the slice returned by UserService.GetLines.

type UserProfile

type UserProfile struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Messenger string `json:"messenger"`
}

UserProfile is one entry of the slice returned by UserService.GetProfiles.

type UserService

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

UserService groups the User endpoints of the adsefid.com API. Obtain one via Client.User rather than constructing it directly.

func (*UserService) GetInfo

func (u *UserService) GetInfo(ctx context.Context) (*UserInfo, error)

GetInfo fetches the authenticated account's general information.

func (*UserService) GetLines

func (u *UserService) GetLines(ctx context.Context) ([]UserLine, error)

GetLines fetches the authenticated account's SMS lines.

func (*UserService) GetProfiles

func (u *UserService) GetProfiles(ctx context.Context) ([]UserProfile, error)

GetProfiles fetches the authenticated account's Messenger profiles.

func (*UserService) GetTemplates

GetTemplates fetches a page of the authenticated account's message templates. A nil req lists the first page in every state.

type UserTemplate

type UserTemplate struct {
	TemplateID  string                           `json:"template_id"`
	Content     string                           `json:"content"`
	Parameters  map[string]TemplateParameterType `json:"parameters"`
	State       TemplateState                    `json:"state"`
	Description *string                          `json:"description"`
	CreatedAt   time.Time                        `json:"created_at"`
	UpdatedAt   time.Time                        `json:"updated_at"`
}

UserTemplate is one entry of GetUserTemplatesResponse.Items.

func (*UserTemplate) UnmarshalJSON

func (u *UserTemplate) UnmarshalJSON(data []byte) error

UnmarshalJSON keeps the documented public parameter-type set forward-compatible when the service emits an undocumented value.

type ValidationError

type ValidationError struct {
	// Field is the name of the offending request field, when known.
	Field string
	// Message describes what is wrong with Field.
	Message string
}

ValidationError reports a client-side pre-flight validation failure. It is returned before any network request is made.

func (*ValidationError) Error

func (e *ValidationError) Error() string

type WebServiceMessageStatus

type WebServiceMessageStatus int

WebServiceMessageStatus is the status of a single SMS or Messenger message, as reported by the get-status endpoints, the send endpoints, and webhook status-update payloads. Values 1000-1999. See doc section 3.2.

const (
	WebServiceMessageStatusScheduled          WebServiceMessageStatus = 1000
	WebServiceMessageStatusSending            WebServiceMessageStatus = 1001
	WebServiceMessageStatusDelivered          WebServiceMessageStatus = 1002
	WebServiceMessageStatusUndelivered        WebServiceMessageStatus = 1003
	WebServiceMessageStatusCanceled           WebServiceMessageStatus = 1004
	WebServiceMessageStatusSentToOperator     WebServiceMessageStatus = 1005
	WebServiceMessageStatusBlacklisted        WebServiceMessageStatus = 1006
	WebServiceMessageStatusProviderError      WebServiceMessageStatus = 1007
	WebServiceMessageStatusPendingApproval    WebServiceMessageStatus = 1008
	WebServiceMessageStatusRejected           WebServiceMessageStatus = 1009
	WebServiceMessageStatusInvalidSender      WebServiceMessageStatus = 1010
	WebServiceMessageStatusInvalidAttachment  WebServiceMessageStatus = 1011
	WebServiceMessageStatusForbiddenWord      WebServiceMessageStatus = 1012
	WebServiceMessageStatusLinkNotAllowed     WebServiceMessageStatus = 1013
	WebServiceMessageStatusInvalidReceiver    WebServiceMessageStatus = 1014
	WebServiceMessageStatusUndeliverable      WebServiceMessageStatus = 1015
	WebServiceMessageStatusSenderLimitReached WebServiceMessageStatus = 1016
	WebServiceMessageStatusUnknown            WebServiceMessageStatus = 1999
)

func MessageStatusOf added in v0.4.0

func MessageStatusOf(code int) (WebServiceMessageStatus, bool)

MessageStatusOf splits a raw per-item WebServiceCode: it returns the WebServiceMessageStatus and true when code is in 1000-1999 and names a status this SDK knows, otherwise 0 and false.

func (WebServiceMessageStatus) String

func (v WebServiceMessageStatus) String() string

type WebServiceResponseCode

type WebServiceResponseCode int

WebServiceResponseCode is the API's error code, carried in the error envelope's error.code field. Values 2000-2047. See doc section 3.4.

const (
	WebServiceResponseCodeInternalError                 WebServiceResponseCode = 2000
	WebServiceResponseCodeInvalidPlan                   WebServiceResponseCode = 2001
	WebServiceResponseCodeLineNotFound                  WebServiceResponseCode = 2002
	WebServiceResponseCodeTooManyReceptors              WebServiceResponseCode = 2003
	WebServiceResponseCodeInvalidLine                   WebServiceResponseCode = 2004
	WebServiceResponseCodeInvalidAPIKey                 WebServiceResponseCode = 2005
	WebServiceResponseCodeIPNotAllowed                  WebServiceResponseCode = 2006
	WebServiceResponseCodeDuplicateLocalID              WebServiceResponseCode = 2007
	WebServiceResponseCodeUserInformationNotFound       WebServiceResponseCode = 2008
	WebServiceResponseCodeEmptyReceptors                WebServiceResponseCode = 2009
	WebServiceResponseCodeInvalidReceptors              WebServiceResponseCode = 2010
	WebServiceResponseCodeEmptyBody                     WebServiceResponseCode = 2011
	WebServiceResponseCodeEmptyLine                     WebServiceResponseCode = 2012
	WebServiceResponseCodeEmptyMessage                  WebServiceResponseCode = 2013
	WebServiceResponseCodeInvalidReceptor               WebServiceResponseCode = 2014
	WebServiceResponseCodeEmptyReceptor                 WebServiceResponseCode = 2015
	WebServiceResponseCodeMessageTooLarge               WebServiceResponseCode = 2016
	WebServiceResponseCodeInvalidLineSelector           WebServiceResponseCode = 2017
	WebServiceResponseCodeUnauthorized                  WebServiceResponseCode = 2018
	WebServiceResponseCodeInvalidSendRange              WebServiceResponseCode = 2019
	WebServiceResponseCodeAllReceptorsBlacklisted       WebServiceResponseCode = 2020
	WebServiceResponseCodeMessageContainsForbiddenWords WebServiceResponseCode = 2021
	WebServiceResponseCodeNotEnoughCredit               WebServiceResponseCode = 2022
	WebServiceResponseCodeDuplicateTag                  WebServiceResponseCode = 2023
	WebServiceResponseCodeInvalidParameter              WebServiceResponseCode = 2024
	WebServiceResponseCodeReceptorBlacklisted           WebServiceResponseCode = 2025
	WebServiceResponseCodeInvalidLinkInMessage          WebServiceResponseCode = 2026
	WebServiceResponseCodeTemplateNotApproved           WebServiceResponseCode = 2027
	WebServiceResponseCodeInvalidTemplateParameter      WebServiceResponseCode = 2028
	WebServiceResponseCodeInvalidLocalIDs               WebServiceResponseCode = 2029
	WebServiceResponseCodeEmptyLocalIDs                 WebServiceResponseCode = 2030
	WebServiceResponseCodeEmptyMessageIDs               WebServiceResponseCode = 2031
	WebServiceResponseCodeInvalidSmsType                WebServiceResponseCode = 2032
	WebServiceResponseCodeLineNotActive                 WebServiceResponseCode = 2033
	WebServiceResponseCodeLineExpired                   WebServiceResponseCode = 2034
	WebServiceResponseCodeMessageLimitReached           WebServiceResponseCode = 2035
	WebServiceResponseCodeRequestLimitReached           WebServiceResponseCode = 2036
	WebServiceResponseCodeInvalidSendTime               WebServiceResponseCode = 2037
	WebServiceResponseCodeInvalidExpiry                 WebServiceResponseCode = 2038
	WebServiceResponseCodeInvalidTemplateID             WebServiceResponseCode = 2039
	WebServiceResponseCodeProfileNotFound               WebServiceResponseCode = 2040
	WebServiceResponseCodeProfileExpired                WebServiceResponseCode = 2041
	WebServiceResponseCodeFileNotFound                  WebServiceResponseCode = 2042
	WebServiceResponseCodeInvalidFile                   WebServiceResponseCode = 2043
	WebServiceResponseCodeAccessDenied                  WebServiceResponseCode = 2044
	WebServiceResponseCodeRejected                      WebServiceResponseCode = 2045
	WebServiceResponseCodeInvalidMessageIDs             WebServiceResponseCode = 2046
	WebServiceResponseCodeFileTooLarge                  WebServiceResponseCode = 2047
)

func ErrorCodeOf added in v0.4.0

func ErrorCodeOf(code int) (WebServiceResponseCode, bool)

ErrorCodeOf splits a raw per-item WebServiceCode: it returns the WebServiceResponseCode and true when code is 2000 or above and names an error this SDK knows, otherwise 0 and false.

func (WebServiceResponseCode) String

func (v WebServiceResponseCode) String() string

type WebhookVerificationError

type WebhookVerificationError struct {
	Message string
}

WebhookVerificationError reports a failure to verify or parse an inbound webhook delivery: a bad signature, a stale timestamp, or a malformed or unrecognized payload.

func (*WebhookVerificationError) Error

func (e *WebhookVerificationError) Error() string

Directories

Path Synopsis
examples
account command
Command account reads the account-level endpoints and shows how to configure the client beyond the defaults.
Command account reads the account-level endpoints and shows how to configure the client beyond the defaults.
bulkandp2p command
Command bulkandp2p demonstrates the two multi-receptor SMS endpoints and, more importantly, how to read a partial success.
Command bulkandp2p demonstrates the two multi-receptor SMS endpoints and, more importantly, how to read a partial success.
messenger command
Command messenger demonstrates the Messenger resource end to end: uploading an attachment, sending it, and checking delivery status.
Command messenger demonstrates the Messenger resource end to end: uploading an attachment, sending it, and checking delivery status.
quickstart command
Command quickstart demonstrates constructing an adsefid.Client, sending a single SMS message, and triaging the possible error types.
Command quickstart demonstrates constructing an adsefid.Client, sending a single SMS message, and triaging the possible error types.
statusandcancel command
Command statusandcancel demonstrates the SMS lookup endpoints: checking delivery status by ID, cancelling scheduled messages, and reading inbound messages.
Command statusandcancel demonstrates the SMS lookup endpoints: checking delivery status by ID, cancelling scheduled messages, and reading inbound messages.
templates command
Command templates lists the account's approved templates and sends one.
Command templates lists the account's approved templates and sends one.
webhookserver command
Command webhookserver runs a minimal HTTP server that receives, verifies, and dispatches adsefid.com webhook deliveries.
Command webhookserver runs a minimal HTTP server that receives, verifies, and dispatches adsefid.com webhook deliveries.
Package webhooks verifies and parses inbound webhook deliveries from the adsefid.com SMS Web Service.
Package webhooks verifies and parses inbound webhook deliveries from the adsefid.com SMS Web Service.

Jump to

Keyboard shortcuts

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