nes

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2026 License: MIT Imports: 18 Imported by: 0

README

nes-go-sdk

Product-ready Go SDK for NES Developer APIs.

Package API Ops (approx.)
einvoice E-Fatura 143
earchive E-Arşiv 103
edespatch E-İrsaliye 161
esmm E-SMM 88
emm E-MM 87
general Account / General 92

Root package nes wires all services with shared Bearer auth, environments, retries and upload helpers.

Separate from the nes-portal worker — no MSSQL / scheduler dependency.

Install

go get github.com/dgmosdev/nes-go-sdk@latest

Local checkout:

cd nes-go-sdk
make ci

Quick start

client, err := nes.New(
    nes.WithAPIKey("YOUR_API_KEY"),
    nes.WithEnvironment(nes.EnvTest), // or nes.EnvProduction
    nes.WithMaxRetries(2),            // optional, GET only
)
if err != nil {
    log.Fatal(err)
}

resp, err := client.EInvoice.GetV1IncomingInvoicesWithResponse(
    context.Background(),
    &einvoice.GetV1IncomingInvoicesParams{
        PageSize: 20,
        Page:     1,
        Sort:     "issueDate:desc",
    },
)
if err != nil {
    log.Fatal(err)
}
if err := nes.EnsureOK(resp.StatusCode(), resp.Body, nes.ResponseMeta(resp.HTTPResponse)); err != nil {
    log.Fatal(err)
}
Upload
resp, err := client.UploadEInvoice(ctx, nes.UploadDocumentParams{
    FilePath:     "./invoice.xml",
    SenderAlias:  "urn:mail:defaultgb@example.com",
    IsDirectSend: true,
    SourceApp:    "DGMOS",
})

Options

Option Description
WithAPIKey Required Bearer token
WithEnvironment EnvTest / EnvProduction
WithRootURL Custom host (tests / proxies)
WithHTTPClient Inject transport / tracing
WithTimeout Default client timeout (60s)
WithUserAgent Override User-Agent (nes-go-sdk/1.0.0)
WithMaxRetries Retry GET/HEAD on 429/5xx
WithRetryWait Base backoff for retries

Errors

if apiErr, ok := err.(*nes.APIError); ok {
    switch {
    case apiErr.Forbidden():
    case apiErr.Temporary():
    case apiErr.NotFound():
    }
}

For generated *WithResponse calls, prefer:

nes.EnsureOK(resp.StatusCode(), resp.Body, method, url)

Layout

nes-go-sdk/
├── nes (root)     Client, options, errors, upload, retry
├── einvoice/      generated
├── earchive/
├── edespatch/
├── esmm/
├── emm/
├── general/
├── openapi/       OpenAPI sources for codegen
├── scripts/       generate.sh
└── examples/basic/

Development

make ci          # tidy + vet + race tests + example build
make generate    # regenerate from openapi/*.openapi.json
make test

# live API (optional)
NES_API_KEY=... go test -tags=integration -count=1 .

Production checklist

  • Typed clients for all 6 NES APIs
  • Bearer auth on every request
  • Test + Production hosts
  • Context-aware HTTP
  • Structured APIError + errors.As
  • Upload multipart helpers with validation
  • Optional idempotent GET retries
  • Concurrent-safe client after New
  • Unit tests (httptest, race detector)
  • Integration test tag
  • Example + README + CHANGELOG + LICENSE
  • CI workflow (make ci)
  • No secrets in repo (.env.example only)

License

MIT

Documentation

Overview

Package nes is the official-style Go SDK for NES Developer APIs (e-Fatura, e-Arşiv, e-İrsaliye, e-SMM, e-MM and General/Account).

The low-level typed clients under einvoice/, earchive/, edespatch/, esmm/, emm/ and general/ are generated from the public OpenAPI specs. This root package wires them together with shared auth, environments and error handling.

Index

Constants

View Source
const (
	PrefixEInvoice  = "/einvoice"
	PrefixEArchive  = "/earchive"
	PrefixEDespatch = "/edespatch"
	PrefixESMM      = "/esmm"
	PrefixEMM       = "/emm"
	PrefixGeneral   = "/general"
)

API prefixes used by NES services.

View Source
const Version = "1.0.0"

Version is the SDK semantic version reported in the default User-Agent.

Variables

This section is empty.

Functions

func CheckResponse

func CheckResponse(resp *http.Response) error

CheckResponse returns nil for 2xx, otherwise an *APIError. On error the response body is consumed.

func EnsureOK

func EnsureOK(statusCode int, body []byte, method, rawURL string) error

EnsureOK converts a buffered non-2xx API result into *APIError.

func ResponseMeta

func ResponseMeta(httpResp *http.Response) (method, rawURL string)

ResponseMeta extracts method/URL from a generated response's HTTPResponse.

Types

type APIError

type APIError struct {
	StatusCode int
	Method     string
	URL        string
	Body       string
	Payload    map[string]any
}

APIError is returned when NES responds with a non-2xx status.

func NewAPIError

func NewAPIError(resp *http.Response) *APIError

NewAPIError builds an APIError from an HTTP response and consumes the body. Safe when resp or resp.Request is nil.

func NewAPIErrorFromParts

func NewAPIErrorFromParts(statusCode int, method, rawURL string, body []byte) *APIError

NewAPIErrorFromParts builds an APIError when the body was already buffered (typical for oapi-codegen *WithResponse helpers).

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Forbidden

func (e *APIError) Forbidden() bool

Forbidden reports HTTP 403 (often missing scope).

func (*APIError) NotFound

func (e *APIError) NotFound() bool

NotFound reports HTTP 404.

func (*APIError) Temporary

func (e *APIError) Temporary() bool

Temporary reports whether the caller may retry.

func (*APIError) Unauthorized

func (e *APIError) Unauthorized() bool

Unauthorized reports HTTP 401.

type Client

type Client struct {
	HTTPClient *http.Client

	EInvoice  *einvoice.ClientWithResponses
	EArchive  *earchive.ClientWithResponses
	EDespatch *edespatch.ClientWithResponses
	ESMM      *esmm.ClientWithResponses
	EMM       *emm.ClientWithResponses
	General   *general.ClientWithResponses
	// contains filtered or unexported fields
}

Client is the unified NES SDK entrypoint.

A Client is safe for concurrent use by multiple goroutines after construction.

func New

func New(opts ...Option) (*Client, error)

New constructs a NES client. An API key is required.

func (*Client) APIKeyConfigured

func (c *Client) APIKeyConfigured() bool

APIKeyConfigured reports whether an API key was provided (value is never exposed).

func (*Client) Environment

func (c *Client) Environment() Environment

Environment returns the selected environment. When WithRootURL is used, the custom URL string is returned as Environment.

func (*Client) RootURL

func (c *Client) RootURL() string

RootURL returns the configured API root host.

func (*Client) UploadEArchive

UploadEArchive uploads a UBL document to the e-archive API.

func (*Client) UploadEInvoice

UploadEInvoice uploads a UBL document to the e-invoice API.

type Environment

type Environment string

Environment selects the NES API host.

const (
	// EnvTest is the NES test/sandbox host (apitest.nes.com.tr).
	EnvTest Environment = "test"
	// EnvProduction is the NES production host (api.nes.com.tr).
	EnvProduction Environment = "production"
)

func (Environment) RootURL

func (e Environment) RootURL() string

RootURL returns the scheme+host for the environment (without API prefix).

type Option

type Option func(*config)

Option configures a Client.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the Bearer API key used for all requests.

func WithEnvironment

func WithEnvironment(env Environment) Option

WithEnvironment sets Test or Production hosts.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient injects a custom http.Client (retries, tracing, etc.). When set, WithTimeout only applies if the client timeout is zero.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries enables idempotent GET retries on 429/5xx and network errors. Non-GET methods are never retried. Default is 0 (disabled).

func WithRetryWait

func WithRetryWait(d time.Duration) Option

WithRetryWait sets the base backoff between retries (exponential: wait * 2^attempt).

func WithRootURL

func WithRootURL(root string) Option

WithRootURL overrides the host root (e.g. httptest URL or reverse proxy). Example: https://apitest.nes.com.tr

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the default timeout on the SDK-owned http.Client when WithHTTPClient is not provided (or when the injected client has Timeout=0).

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent overrides the User-Agent header.

type UploadDocumentParams

type UploadDocumentParams struct {
	FilePath      string
	FileName      string
	File          io.Reader // optional alternative to FilePath
	SenderAlias   string
	ReceiverAlias string
	IsDirectSend  bool
	SourceApp     string
	// AutoSaveCompany defaults to true when nil.
	AutoSaveCompany *bool
	// PreviewType e.g. "None" (default).
	PreviewType string
}

UploadDocumentParams are common fields for e-invoice / e-archive uploads.

Directories

Path Synopsis
Package earchive provides primitives to interact with the openapi HTTP API.
Package earchive provides primitives to interact with the openapi HTTP API.
Package edespatch provides primitives to interact with the openapi HTTP API.
Package edespatch provides primitives to interact with the openapi HTTP API.
Package einvoice provides primitives to interact with the openapi HTTP API.
Package einvoice provides primitives to interact with the openapi HTTP API.
Package emm provides primitives to interact with the openapi HTTP API.
Package emm provides primitives to interact with the openapi HTTP API.
Package esmm provides primitives to interact with the openapi HTTP API.
Package esmm provides primitives to interact with the openapi HTTP API.
examples
basic command
Package general provides primitives to interact with the openapi HTTP API.
Package general provides primitives to interact with the openapi HTTP API.

Jump to

Keyboard shortcuts

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