ggsel

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 20 Imported by: 0

README

go-ggsel-api

Go Reference Go 1.26 CI

Неофициальный клиент официального Seller API GGSel. Один модуль github.com/Zoomish/go-ggsel-api, пакет ggsel, оба контура, база https://seller.ggsel.com. Это не клиент компании GGSel и не автовыдача.

English · документация пакета

Содержание

Установка

go get github.com/Zoomish/go-ggsel-api

Быстрый старт

New только собирает клиент и не открывает соединение. Дедлайн задаётся через context.

client, err := ggsel.New(ggsel.Options{
    APIKey: os.Getenv("GGSEL_API_KEY"),
})
if err != nil {
    return err
}
page, err := client.ListOffers(ctx, ggsel.ListOffersParams{})

Ключ v2 уходит в заголовок Authorization как есть, без Bearer.

Без ключа пример не открывает сеть и завершается с кодом 0:

go run ./examples/list_offers

Контур v1

Для заказа, уникального кода и чатов нужен SellerID. Token вызывающий не передаёт и не видит: клиент сам делает apilogin и подставляет query-параметр.

client, err := ggsel.New(ggsel.Options{
    APIKey:   os.Getenv("GGSEL_API_KEY"),
    SellerID: sellerID,
})
order, err := client.GetOrder(ctx, invoiceID)

Деньги и частичное обновление

Цены и суммы — ggsel.Decimal поверх shopspring/decimal, не float64. В JSON уходит число.

В OfferWrite nil-поле не сериализуется. Ptr(false), ноль и пустая строка уходят.

_, err = client.UpdateOffer(ctx, offerID, ggsel.OfferWrite{
    IsAutoselling: ggsel.Ptr(false),
})

Ошибки

var apiErr *ggsel.APIError
if errors.As(err, &apiErr) {
    // apiErr.StatusCode, apiErr.RetVal, apiErr.Errors
}
if ggsel.IsUnauthorized(err) {
    // HTTP 401
}

Error() не содержит ключ, sign и token.

Повторы

Повторяются только безопасные GET. 401 и отказ apilogin не повторяются. POST и PATCH, включая создание оффера и отправку сообщения, тоже не повторяются.

Что входит в модуль

Сейчас это офферы и категории v2, а в v1 — заказ, уникальный код и чаты. Полный список методов — на pkg.go.dev.

В модуле нет пакетных activate/pause/delete, опций, товаров, остальных методов v1 и XML shop_search.asp.

Контракт

Пути и поля взяты из публичной документации Seller API. Клиент на seller.ggsel.com за спецификацией не ходит. Оба снимка лежат в testdata/seller-api-v1.openapi.json и testdata/seller-api-v2.openapi.json. Раз в месяц go run ./cmd/docscheck сравнивает их с сайтом.

Безопасность

Не кладите API-ключ, sign и token в issue и pull request. Как сообщать об уязвимости: SECURITY.md.

Лицензия

MIT.

Documentation

Overview

Package ggsel — неофициальный клиент Seller API GGSel.

Дедлайн запроса — более раннее из context вызывающего кода и Timeout клиента. Если HTTP-клиент не передан, Timeout равен 30 секундам.

Логический отказ v1 — это APIError со статусом пришедшего ответа, в том числе 200. IsUnauthorized к такому отказу не относится.

Повторяются только помеченные безопасные GET. 401 и отказ apilogin не повторяются.

Index

Examples

Constants

View Source
const (
	// DefaultBaseURL — база Seller API, если Options.BaseURL пуст.
	DefaultBaseURL = "https://seller.ggsel.com"
)

Variables

View Source
var ErrSellerIDRequired = errors.New("ggsel: seller id is required")

ErrSellerIDRequired возвращается, если метод v1 вызван без SellerID.

Functions

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized сообщает, что API ответил HTTP 401.

func Ptr

func Ptr[T any](v T) *T

Ptr возвращает указатель на v. Нужен, чтобы отправить false, 0 или пустую строку.

Types

type APIError

type APIError struct {
	StatusCode int
	Method     string
	Path       string
	Body       []byte
	RetVal     *int
	RetDesc    string
	Desc       string
	Errors     []APIErrorItem
}

APIError — ответ Seller API, который не разобран как успех. Error не содержит тело, ключ и token. Тело лежит в Body.

func (*APIError) Error

func (e *APIError) Error() string

type APIErrorEntity

type APIErrorEntity struct {
	ID          *int64
	Resource    string
	Description string
}

APIErrorEntity — объект entity у ошибки v2.

type APIErrorItem

type APIErrorItem struct {
	Code   string
	Entity *APIErrorEntity
}

APIErrorItem — элемент errors[] контура v2.

type Buyer

type Buyer struct {
	PaymentMethod     string  `json:"payment_method"`
	Account           string  `json:"account"`
	Email             *string `json:"email"`
	Phone             *string `json:"phone"`
	Skype             *string `json:"skype"`
	WhatsApp          *string `json:"whatsapp"`
	IPAddress         *string `json:"ip_address"`
	PaymentAggregator string  `json:"payment_aggregator"`
}

Buyer — покупатель заказа.

type Category

type Category struct {
	ID          int64   `json:"id"`
	Title       string  `json:"title"`
	ContentType string  `json:"content_type"`
	Fee         Decimal `json:"fee"`
	PaymentFee  Decimal `json:"payment_fee"`
	Tree        string  `json:"tree"`
	HasChildren bool    `json:"has_children"`
}

Category — категория v2. Fee и PaymentFee — доли комиссии, не float64.

type CategoryPage

type CategoryPage struct {
	Categories []Category
	Pagination Pagination
}

CategoryPage — одна страница категорий.

type CategoryPageParams

type CategoryPageParams struct {
	Page  *int64
	Limit *int64
}

CategoryPageParams — page и limit. Нулевые указатели в запрос не попадают.

type Chat

type Chat struct {
	InvoiceID    int64  `json:"id_i"`
	Email        string `json:"email"`
	ProductID    int64  `json:"product"`
	LastMessage  string `json:"last_message"`
	MessageCount *int64 `json:"cnt_msg"`
	NewCount     *int64 `json:"cnt_new"`
}

Chat — диалог с покупателем.

type ChatPage

type ChatPage struct {
	PageCount int64  `json:"cnt_pages"`
	Items     []Chat `json:"items"`
}

ChatPage — страница списка чатов.

type Client

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

Client вызывает Seller API. Его можно использовать из нескольких горутин. New не ходит в сеть.

func New

func New(opts Options) (*Client, error)

New собирает клиент. Пустой ключ — ошибка. SellerID может быть нулём: он нужен только методам контура v1.

Example
package main

import (
	"github.com/Zoomish/go-ggsel-api"
)

func main() {
	if _, err := ggsel.New(ggsel.Options{}); err == nil {
		panic("empty key")
	}
	client, err := ggsel.New(ggsel.Options{APIKey: "test-key"})
	if err != nil || client == nil {
		panic(err)
	}
}

func (*Client) CheckUniqueCode

func (c *Client) CheckUniqueCode(ctx context.Context, code string) (UniqueCode, error)

CheckUniqueCode проверяет уникальный код заказа.

func (*Client) CreateOffer

func (c *Client) CreateOffer(ctx context.Context, body OfferWrite) (Offer, error)

CreateOffer создаёт оффер. Повтор запроса не выполняется.

func (*Client) GetOffer

func (c *Client) GetOffer(ctx context.Context, id int64) (Offer, error)

GetOffer возвращает карточку оффера.

func (*Client) GetOrder

func (c *Client) GetOrder(ctx context.Context, invoiceID int64) (Order, error)

GetOrder возвращает заказ по номеру счёта.

Example
package main

import (
	"context"
	"errors"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/Zoomish/go-ggsel-api"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/api_sellers/api/apilogin" {
			w.Header().Set("Content-Type", "application/json")
			_, _ = io.WriteString(w, `{"retval":0,"token":"tok","valid_thru":"2099-01-01T00:00:00Z"}`)
			return
		}
		w.WriteHeader(http.StatusUnauthorized)
		_, _ = io.WriteString(w, `{"retval":-1,"retdesc":"no"}`)
	}))
	defer srv.Close()

	client, err := ggsel.New(ggsel.Options{
		APIKey:   "test-key",
		SellerID: 42,
		BaseURL:  srv.URL,
	})
	if err != nil {
		panic(err)
	}
	_, err = client.GetOrder(context.Background(), 15)
	var apiErr *ggsel.APIError
	if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusUnauthorized {
		panic(err)
	}
}

func (*Client) ListCategories

func (c *Client) ListCategories(ctx context.Context, params ListCategoriesParams) (CategoryPage, error)

ListCategories возвращает одну страницу категорий.

func (*Client) ListChats

func (c *Client) ListChats(ctx context.Context, params ListChatsParams) (ChatPage, error)

ListChats возвращает страницу чатов.

func (*Client) ListMessages

func (c *Client) ListMessages(ctx context.Context, invoiceID int64, params ListMessagesParams) ([]Message, error)

ListMessages возвращает сообщения заказа. Успешный ответ — JSON-массив.

func (*Client) ListOffers

func (c *Client) ListOffers(ctx context.Context, params ListOffersParams) (OfferPage, error)

ListOffers возвращает одну страницу офферов.

Example
package main

import (
	"context"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/Zoomish/go-ggsel-api"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, `{
			"data":[{
				"id":1,
				"status":"active",
				"price":19.99,
				"currency":"RUB",
				"category":{"id":3,"title":"Games","content_type":"key","fee":0,"payment_fee":0,"tree":"Games","has_children":false},
				"has_options":false,
				"has_products":false,
				"has_splitted_products":false,
				"cover_image_ru_url":""
			}],
			"pagination":{"page":1,"limit":100,"has_next_page":false,"has_previous_page":false}
		}`)
	}))
	defer srv.Close()

	client, err := ggsel.New(ggsel.Options{APIKey: "test-key", BaseURL: srv.URL})
	if err != nil {
		panic(err)
	}
	page, err := client.ListOffers(context.Background(), ggsel.ListOffersParams{})
	if err != nil {
		panic(err)
	}
	if len(page.Offers) != 1 || page.Offers[0].Price == nil || page.Offers[0].Price.String() != "19.99" {
		panic(page.Offers)
	}
}

func (*Client) Login

func (c *Client) Login(ctx context.Context) error

Login получает token v1. Кэш пустеет за 30 секунд до valid_thru. Если valid_thru не разбирается, token этого вызова возвращается, но в кэш не кладётся. Методы v1 вызывают вход сами, если кэш пуст.

func (*Client) SearchCategories

func (c *Client) SearchCategories(ctx context.Context, query string, params CategoryPageParams) (CategoryPage, error)

SearchCategories ищет категории по q. Пустой запрос не уходит в сеть.

func (*Client) SendMessage

func (c *Client) SendMessage(ctx context.Context, invoiceID int64, text string) error

SendMessage отправляет текст в чат заказа. Пустой текст в сеть не уходит.

func (*Client) UpdateOffer

func (c *Client) UpdateOffer(ctx context.Context, id int64, body OfferWrite) (Offer, error)

UpdateOffer частично обновляет оффер. Повтор запроса не выполняется.

Example
package main

import (
	"context"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/Zoomish/go-ggsel-api"
)

func main() {
	var raw string
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		buf, err := io.ReadAll(r.Body)
		if err != nil {
			panic(err)
		}
		raw = string(buf)
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, `{
			"data":{
				"id":15,"status":"draft","is_autoselling":false,
				"title_ru":"","title_en":"","description_ru":"","description_en":"",
				"instructions_ru":"","instructions_en":"","cover_image_ru_url":"",
				"category":{"id":1,"title":"","content_type":"","fee":0,"payment_fee":0,"tree":"","has_children":false},
				"price":19.99,"currency":"RUB","quantity":0,"is_unlimited_quantity":false,
				"sold_splitted_products_count":0,"sold_products_count":0,
				"in_stock_products_count":0,"in_stock_splitted_products_count":0,
				"has_splitted_products":false,"updated_at":"","created_at":""
			}
		}`)
	}))
	defer srv.Close()

	client, err := ggsel.New(ggsel.Options{APIKey: "test-key", BaseURL: srv.URL})
	if err != nil {
		panic(err)
	}
	price := ggsel.Decimal{}
	if err := price.UnmarshalJSON([]byte("19.99")); err != nil {
		panic(err)
	}
	if _, err := client.UpdateOffer(context.Background(), 15, ggsel.OfferWrite{
		IsAutoselling: ggsel.Ptr(false),
		Price:         &price,
	}); err != nil {
		panic(err)
	}
	if raw != `{"price":19.99,"is_autoselling":false}` || strings.Contains(raw, "title_ru") {
		panic(raw)
	}
}

type Currency

type Currency string

Currency — валюта цены оффера v2. В спецификации это RUB.

const (
	CurrencyRUB Currency = "RUB"
)

type Decimal

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

Decimal — точное десятичное число для полей schema type number. В JSON это число, не строка и не float64.

func (Decimal) Equal

func (d Decimal) Equal(other Decimal) bool

func (Decimal) MarshalJSON

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

func (Decimal) String

func (d Decimal) String() string

func (*Decimal) UnmarshalJSON

func (d *Decimal) UnmarshalJSON(raw []byte) error

type Delivery

type Delivery string

Delivery — способ выдачи оффера.

const (
	DeliveryAuto   Delivery = "auto"
	DeliveryManual Delivery = "manual"
)

type FeedbackType

type FeedbackType string

FeedbackType — тип отзыва покупателя.

const (
	FeedbackPositive FeedbackType = "positive"
	FeedbackNegative FeedbackType = "negative"
)

type InvoiceState

type InvoiceState int

InvoiceState — состояние счёта v1.

const (
	InvoiceStateCreated   InvoiceState = 1
	InvoiceStateCanceled  InvoiceState = 2
	InvoiceStatePaid      InvoiceState = 3
	InvoiceStateCompleted InvoiceState = 4
	InvoiceStateRefunded  InvoiceState = 5
)

type ListCategoriesParams

type ListCategoriesParams struct {
	ParentID *int64
	Page     *int64
	Limit    *int64
}

ListCategoriesParams — фильтр списка категорий.

type ListChatsParams

type ListChatsParams struct {
	FilterNew *int64
	Email     *string
	GoodsID   *string
	PageSize  *int64
	Page      *int64
}

ListChatsParams — фильтр чатов. Нулевые указатели в запрос не попадают.

type ListMessagesParams

type ListMessagesParams struct {
	FromID *int64
	ToID   *int64
	Newer  *int64
	Count  *int64
}

ListMessagesParams — окно сообщений. id_i задаёт метод.

type ListOffersParams

type ListOffersParams struct {
	Page          *int64
	Limit         *int64
	Search        *string
	CategoryID    *int64
	Status        *OfferListStatus
	Sort          *OfferSort
	Delivery      *Delivery
	UpdatedAtFrom *time.Time
}

ListOffersParams — фильтр списка. Нулевые указатели в запрос не попадают.

type Message

type Message struct {
	ID          int64   `json:"id"`
	Text        string  `json:"message"`
	Buyer       int64   `json:"buyer"`
	Seller      int64   `json:"seller"`
	Deleted     *int64  `json:"deleted"`
	DateWritten string  `json:"date_written"`
	DateSeen    *string `json:"date_seen"`
	IsFile      *int64  `json:"is_file"`
	Filename    *string `json:"filename"`
	URL         *string `json:"url"`
	IsImage     *int64  `json:"is_img"`
	Preview     *string `json:"preview"`
}

Message — сообщение переписки.

type NotificationMethod

type NotificationMethod string

NotificationMethod — HTTP-метод уведомления.

const (
	NotificationMethodGET  NotificationMethod = "GET"
	NotificationMethodPOST NotificationMethod = "POST"
)

type NotificationSettings

type NotificationSettings struct {
	Type       *NotificationType   `json:"type"`
	URL        *string             `json:"url"`
	Email      *string             `json:"email"`
	HTTPMethod *NotificationMethod `json:"http_method"`
	IsDisabled bool                `json:"is_disabled"`
	IsDefault  bool                `json:"is_default"`
}

NotificationSettings — уведомление продавца о новом заказе.

type NotificationSettingsWrite

type NotificationSettingsWrite struct {
	Type       *NotificationType   `json:"type,omitempty"`
	URL        *string             `json:"url,omitempty"`
	Email      *string             `json:"email,omitempty"`
	HTTPMethod *NotificationMethod `json:"http_method,omitempty"`
	IsDisabled *bool               `json:"is_disabled,omitempty"`
	IsDefault  *bool               `json:"is_default,omitempty"`
}

NotificationSettingsWrite — частичные настройки уведомления о заказе.

type NotificationType

type NotificationType string

NotificationType — канал уведомления продавца о заказе.

const (
	NotificationEmail NotificationType = "email"
	NotificationURL   NotificationType = "url"
)

type Offer

type Offer struct {
	ID                           int64                 `json:"id"`
	Status                       OfferStatus           `json:"status"`
	IsAutoselling                bool                  `json:"is_autoselling"`
	Delivery                     *Delivery             `json:"delivery"`
	TitleRU                      string                `json:"title_ru"`
	TitleEN                      string                `json:"title_en"`
	DescriptionRU                string                `json:"description_ru"`
	DescriptionEN                string                `json:"description_en"`
	InstructionsRU               string                `json:"instructions_ru"`
	InstructionsEN               string                `json:"instructions_en"`
	CoverImageRUURL              string                `json:"cover_image_ru_url"`
	CoverImageENURL              *string               `json:"cover_image_en_url"`
	Category                     Category              `json:"category"`
	Price                        Decimal               `json:"price"`
	Currency                     Currency              `json:"currency"`
	Quantity                     int64                 `json:"quantity"`
	IsUnlimitedQuantity          bool                  `json:"is_unlimited_quantity"`
	MinQuantity                  *int64                `json:"min_quantity"`
	MaxQuantity                  *int64                `json:"max_quantity"`
	SoldSplittedProductsCount    int64                 `json:"sold_splitted_products_count"`
	SoldProductsCount            int64                 `json:"sold_products_count"`
	InStockProductsCount         int64                 `json:"in_stock_products_count"`
	InStockSplittedProductsCount int64                 `json:"in_stock_splitted_products_count"`
	HasSplittedProducts          bool                  `json:"has_splitted_products"`
	UpdatedAt                    string                `json:"updated_at"`
	CreatedAt                    string                `json:"created_at"`
	PostPaymentURL               *string               `json:"post_payment_url"`
	PrePaymentSettings           *PrePaymentSettings   `json:"pre_payment_settings"`
	NotificationSettings         *NotificationSettings `json:"notification_settings"`
}

Offer — карточка оффера. Её же возвращают создание и обновление.

type OfferListStatus

type OfferListStatus string

OfferListStatus — фильтр списка. Archived в этот фильтр не входит.

const (
	OfferListStatusActive OfferListStatus = "active"
	OfferListStatusPaused OfferListStatus = "paused"
	OfferListStatusDraft  OfferListStatus = "draft"
)

type OfferPage

type OfferPage struct {
	Offers     []OfferSummary
	Pagination Pagination
}

OfferPage — одна страница списка офферов.

type OfferSort

type OfferSort string

OfferSort — сортировка списка офферов.

const (
	OfferSortPriceAsc          OfferSort = "price_asc"
	OfferSortPriceDesc         OfferSort = "price_desc"
	OfferSortSalesCountAsc     OfferSort = "sales_count_asc"
	OfferSortSalesCountDesc    OfferSort = "sales_count_desc"
	OfferSortProductsCountAsc  OfferSort = "products_count_asc"
	OfferSortProductsCountDesc OfferSort = "products_count_desc"
)

type OfferStatus

type OfferStatus string

OfferStatus — статус оффера в карточке и списке.

const (
	OfferStatusDraft    OfferStatus = "draft"
	OfferStatusActive   OfferStatus = "active"
	OfferStatusPaused   OfferStatus = "paused"
	OfferStatusArchived OfferStatus = "archived"
)

type OfferSummary

type OfferSummary struct {
	ID                   int64                 `json:"id"`
	Status               OfferStatus           `json:"status"`
	TitleRU              *string               `json:"title_ru"`
	TitleEN              *string               `json:"title_en"`
	DescriptionRU        *string               `json:"description_ru"`
	DescriptionEN        *string               `json:"description_en"`
	Price                *Decimal              `json:"price"`
	Currency             Currency              `json:"currency"`
	IsAutoselling        *bool                 `json:"is_autoselling"`
	Category             Category              `json:"category"`
	MinQuantity          *int64                `json:"min_quantity"`
	MaxQuantity          *int64                `json:"max_quantity"`
	Quantity             *int64                `json:"quantity"`
	IsUnlimitedQuantity  *bool                 `json:"is_unlimited_quantity"`
	InstructionsRU       *string               `json:"instructions_ru"`
	InstructionsEN       *string               `json:"instructions_en"`
	PostPaymentURL       *string               `json:"post_payment_url"`
	Delivery             *Delivery             `json:"delivery"`
	CoverImageRUURL      string                `json:"cover_image_ru_url"`
	CoverImageENURL      *string               `json:"cover_image_en_url"`
	HasOptions           bool                  `json:"has_options"`
	HasProducts          bool                  `json:"has_products"`
	HasSplittedProducts  bool                  `json:"has_splitted_products"`
	CreatedAt            string                `json:"created_at"`
	UpdatedAt            string                `json:"updated_at"`
	PrePaymentSettings   *PrePaymentSettings   `json:"pre_payment_settings"`
	NotificationSettings *NotificationSettings `json:"notification_settings"`
}

OfferSummary — элемент списка офферов.

type OfferWrite

type OfferWrite struct {
	TitleRU              *string                    `json:"title_ru,omitempty"`
	TitleEN              *string                    `json:"title_en,omitempty"`
	DescriptionRU        *string                    `json:"description_ru,omitempty"`
	DescriptionEN        *string                    `json:"description_en,omitempty"`
	InstructionsRU       *string                    `json:"instructions_ru,omitempty"`
	InstructionsEN       *string                    `json:"instructions_en,omitempty"`
	CoverImageRU         *string                    `json:"cover_image_ru,omitempty"`
	CoverImageEN         *string                    `json:"cover_image_en,omitempty"`
	Price                *Decimal                   `json:"price,omitempty"`
	Currency             *Currency                  `json:"currency,omitempty"`
	IsAutoselling        *bool                      `json:"is_autoselling,omitempty"`
	CategoryID           *int64                     `json:"category_id,omitempty"`
	MinQuantity          *int64                     `json:"min_quantity,omitempty"`
	MaxQuantity          *int64                     `json:"max_quantity,omitempty"`
	Quantity             *int64                     `json:"quantity,omitempty"`
	IsUnlimitedQuantity  *bool                      `json:"is_unlimited_quantity,omitempty"`
	PostPaymentURL       *string                    `json:"post_payment_url,omitempty"`
	Delivery             *Delivery                  `json:"delivery,omitempty"`
	PrePaymentSettings   *PrePaymentSettingsWrite   `json:"pre_payment_settings,omitempty"`
	NotificationSettings *NotificationSettingsWrite `json:"notification_settings,omitempty"`
}

OfferWrite — тело создания и частичного обновления оффера. Nil-поле в JSON не попадает.

type Options

type Options struct {
	// BaseURL — база API. Пустое значение равно DefaultBaseURL.
	BaseURL string
	// HTTPClient — свой HTTP-клиент. Nil заменяется клиентом с таймаутом 30 секунд.
	// Переданный клиент не изменяется.
	HTTPClient *http.Client
	// APIKey — ключ продавца. Пустое значение делает New ошибкой.
	APIKey string
	// SellerID — идентификатор продавца для контура v1. Ноль допустим, пока v1 не вызывается.
	SellerID int64
	// Locale — заголовок locale. Пустое значение равно ru.
	Locale string
	// MaxRetries — сколько повторных попыток получает безопасный GET после первой.
	// Ноль равен двум. Отрицательное значение выключает повторы.
	MaxRetries int
	// RetryBackoffMin — нижняя граница паузы между повторами. Ноль равно 100 миллисекундам.
	RetryBackoffMin time.Duration
	// RetryBackoffMax — верхняя граница паузы между повторами. Ноль равно 2 секундам.
	RetryBackoffMax time.Duration
	// Clock — часы для timestamp и срока token. Nil вызывает time.Now.
	Clock func() time.Time
}

Options задаёт клиент. Нулевые поля, кроме APIKey, безопасны. New не выполняет сетевых вызовов.

type Order

type Order struct {
	ItemID          *int64         `json:"item_id"`
	ContentID       int64          `json:"content_id"`
	CartUID         *string        `json:"cart_uid"`
	Name            *string        `json:"name"`
	Amount          Decimal        `json:"amount"`
	CurrencyType    string         `json:"currency_type"`
	InvoiceState    InvoiceState   `json:"invoice_state"`
	PurchaseDate    string         `json:"purchase_date"`
	DatePay         *string        `json:"date_pay"`
	AgentID         *int64         `json:"agent_id"`
	AgentPercent    *Decimal       `json:"agent_percent"`
	AgentFee        Decimal        `json:"agent_fee"`
	QueryString     *string        `json:"query_string"`
	UnitGoods       *string        `json:"unit_goods"`
	CountGoods      *string        `json:"cnt_goods"`
	PromoCode       *string        `json:"promo_code"`
	BonusCode       *string        `json:"bonus_code"`
	Feedback        *OrderFeedback `json:"feedback"`
	UniqueCodeState OrderCodeState `json:"unique_code_state"`
	Options         []OrderOption  `json:"options"`
	Buyer           Buyer          `json:"buyer_info"`
	Owner           int64          `json:"owner"`
	DayLock         int64          `json:"day_lock"`
	LockState       string         `json:"lock_state"`
	Profit          Decimal        `json:"profit"`
	ExternalOrderID *string        `json:"external_order_id"`
}

Order — содержание заказа из purchase/info.

type OrderCodeState

type OrderCodeState struct {
	State         *int64  `json:"state"`
	DateCheck     *string `json:"date_check"`
	DateDelivery  *string `json:"date_delivery"`
	DateConfirmed *string `json:"date_confirmed"`
	DateRefuted   *string `json:"date_refuted"`
}

OrderCodeState — состояние уникального кода в заказе.

type OrderFeedback

type OrderFeedback struct {
	Deleted  bool         `json:"deleted"`
	Feedback string       `json:"feedback"`
	Type     FeedbackType `json:"feedback_type"`
	Comment  *string      `json:"comment"`
}

OrderFeedback — отзыв в карточке заказа.

type OrderOption

type OrderOption struct {
	ID         int64   `json:"id"`
	Name       *string `json:"name"`
	UserData   string  `json:"user_data"`
	UserDataID *int64  `json:"user_data_id"`
}

OrderOption — опция товара в заказе.

type Pagination

type Pagination struct {
	Page            int64  `json:"page"`
	Limit           int64  `json:"limit"`
	HasNextPage     bool   `json:"has_next_page"`
	HasPreviousPage bool   `json:"has_previous_page"`
	TotalPages      int64  `json:"total_pages"`
	TotalCount      *int64 `json:"total_count"`
}

Pagination — страница v2, включая устаревшие total_pages и total_count.

type PrePaymentSettings

type PrePaymentSettings struct {
	IsEnabled    bool    `json:"is_enabled"`
	URL          *string `json:"url"`
	AllowPayment bool    `json:"allow_payment"`
}

PrePaymentSettings — проверка до оплаты.

type PrePaymentSettingsWrite

type PrePaymentSettingsWrite struct {
	IsEnabled    *bool   `json:"is_enabled,omitempty"`
	URL          *string `json:"url,omitempty"`
	AllowPayment *bool   `json:"allow_payment,omitempty"`
}

PrePaymentSettingsWrite — частичные настройки проверки до оплаты.

type UniqueCode

type UniqueCode struct {
	InvoiceID       int64              `json:"inv"`
	GoodsID         int64              `json:"id_goods"`
	Amount          Decimal            `json:"amount"`
	CurrencyType    string             `json:"type_curr"`
	AmountUSD       Decimal            `json:"amount_usd"`
	Profit          Decimal            `json:"profit"`
	DatePay         string             `json:"date_pay"`
	Email           *string            `json:"email"`
	Name            string             `json:"name_invoice"`
	Lang            *string            `json:"lang"`
	AgentID         *int64             `json:"agent_id"`
	AgentPercent    *string            `json:"agent_percent"`
	QueryString     *string            `json:"query_string"`
	UnitGoods       *string            `json:"unit_goods"`
	CountGoods      *string            `json:"cnt_goods"`
	PromoCode       *string            `json:"promo_code"`
	BonusCode       *string            `json:"bonus_code"`
	CartUID         *string            `json:"cart_uid"`
	UniqueCodeState UniqueCodeState    `json:"unique_code_state"`
	Options         []UniqueCodeOption `json:"options"`
}

UniqueCode — результат проверки уникального кода. AgentPercent здесь строка: в этой схеме тип другой, чем у заказа.

type UniqueCodeOption

type UniqueCodeOption struct {
	ID        *int64  `json:"id"`
	Name      *string `json:"name"`
	Value     *string `json:"value"`
	VariantID *int64  `json:"variant_id"`
}

UniqueCodeOption — опция товара в ответе уникального кода.

type UniqueCodeState

type UniqueCodeState struct {
	State         int64   `json:"state"`
	DateCheck     *string `json:"date_check"`
	DateDelivery  *string `json:"date_delivery"`
	DateConfirmed *string `json:"date_confirmed"`
	DateRefuted   *string `json:"date_refuted"`
}

UniqueCodeState — состояние уникального кода при проверке кода.

Directories

Path Synopsis
cmd
docscheck command
examples
list_offers command

Jump to

Keyboard shortcuts

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