goldenpay

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: MIT Imports: 21 Imported by: 0

README

goldenpay-go

Go port of the goldenpay Rust SDK for FunPay automation.

Features

  • Session-based HTTP client with golden key authentication
  • Proxy support
  • Order polling + auto-delivery
  • Offer management (read, edit, create, delete, undercut)
  • Chat messaging via FunPay runner API
  • Price calculator
  • Category tree, filters, subcategories
  • Market offer listing (competitor prices)
  • Webhook server with HMAC verification
  • Offer schedule (activate/deactivate by time)
  • State persistence (memory / JSON)
  • Delivery automation (inventory, message builder, delivery store)
  • Session manager with auto-reconnect on auth errors

Installation

go get github.com/rxzsu/goldenpay-go

Quick start

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/rxzsu/goldenpay-go"
)

func main() {
    key := os.Getenv("GOLDEN_KEY")
    if key == "" {
        log.Fatal("GOLDEN_KEY is required")
    }

    client, err := goldenpay.New(goldenpay.NewConfig(key))
    if err != nil {
        log.Fatal(err)
    }

    session, err := client.Connect()
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Logged in as %s (ID %d)\n", session.User().Username, session.User().ID)

    orders, _ := session.FetchOrders()
    for _, o := range orders {
        fmt.Printf("Order %s: %s (%s)\n", o.ID, o.Description, o.Status)
    }

    balance, _ := session.FetchBalance()
    fmt.Printf("Balance: %.2f\n", balance)
}

Documentation

Full package documentation at pkg.go.dev/github.com/rxzsu/goldenpay-go.

See cmd/example/main.go for a complete example with bot polling.

API

Method Description
FetchOrders() All orders from trade page
FetchPaidOrders() Paid orders only
FetchOrderPage(id) Full order details (secrets, params, review)
SendMessage(chatID, text) Send chat message
FetchChatMessages(chatID) Get chat messages
FetchMyOffers(nodeID) Your offers in a category
FetchOfferDetails(nodeID, offerID) Current offer field values
EditOffer(nodeID, offerID, patch) Patch an offer
CreateOffer(nodeID, details) Create a new offer
UndercutPrice(nodeID, offerID, undercutBy, minPrice) Auto-price below competition
FetchMarketOffers(nodeID) Competitor offers
CalcPrice(nodeID, price) Price breakdown
FetchCategoryTree() Full category tree
FetchBalance() Account balance
RaiseOffers(nodeID) Raise all offers
Ping() Runner heartbeat

License

MIT

Documentation

Overview

Package goldenpay — Go port of the goldenpay Rust SDK for FunPay automation.

Provides session management, order polling, delivery automation, offer editing, chat messaging, webhook server, and offer scheduling.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrProductNotFound   = &DeliveryError{Kind: "ProductNotFound", Message: "product not found"}
	ErrAlreadyDelivered  = &DeliveryError{Kind: "AlreadyDelivered", Message: "order was already delivered"}
	ErrOrderNotPaid      = &DeliveryError{Kind: "OrderNotPaid", Message: "order is not paid"}
	ErrMessageSendFailed = &DeliveryError{Kind: "MessageSendFailed", Message: "delivery message was rejected"}
)

Functions

func HMACSHA256

func HMACSHA256(key, data []byte) []byte

HMACSHA256 computes HMAC-SHA256 of data with the given key.

func IsAuthError

func IsAuthError(err error) bool

IsAuthError checks if the underlying error is an authentication error.

func VerifyHMAC

func VerifyHMAC(key, data, signature []byte) bool

VerifyHMAC checks if signature is a valid HMAC-SHA256 of data under key.

func WebhookSignature

func WebhookSignature(secret string, body []byte) string

WebhookSignature returns the hex-encoded HMAC-SHA256 for webhook headers.

Types

type BotOptions

type BotOptions struct {
	IgnoreOwnMessages        bool
	EmitMessagesForNewOrders bool
	AutoWelcomeMessage       string
	SleepScheduleStart       int
	SleepScheduleEnd         int
	SleepNodeOffers          [][2]int64 // (node_id, offer_id) pairs
}

BotOptions configures the bot.

func DefaultBotOptions

func DefaultBotOptions() BotOptions

type BotState

type BotState struct {
	SeenOrders   []string         `json:"seen_orders"`
	SeenMessages map[string]int64 `json:"seen_messages"`
}

BotState for persistence.

type CategoryFilter

type CategoryFilter struct {
	ID         string                 `json:"id"`
	Name       string                 `json:"name"`
	FilterType string                 `json:"filter_type"` // select, radio, range, checkbox
	Options    []CategoryFilterOption `json:"options"`
}

CategoryFilter is a filter control on the category page.

type CategoryFilterOption

type CategoryFilterOption struct {
	Value string `json:"value"`
	Label string `json:"label"`
}

type CategoryNode

type CategoryNode struct {
	ID              int64          `json:"id"`
	Name            string         `json:"name"`
	SubcategoryType *string        `json:"subcategory_type,omitempty"`
	Children        []CategoryNode `json:"children"`
}

CategoryNode is a node in the marketplace category tree.

type CategorySubcategory

type CategorySubcategory struct {
	ID              int64  `json:"id"`
	Name            string `json:"name"`
	OfferCount      int    `json:"offer_count"`
	SubcategoryType string `json:"subcategory_type"`
	IsActive        bool   `json:"is_active"`
}

CategorySubcategory is a subcategory pill on the category page.

type ChatMessage

type ChatMessage struct {
	ID       int64  `json:"id"`
	ChatID   string `json:"chat_id"`
	AuthorID int64  `json:"author_id"`
	Text     string `json:"text,omitempty"`
}

ChatMessage represents a single chat message.

type DeliveredOrderRecord

type DeliveredOrderRecord struct {
	OrderID    string               `json:"order_id"`
	ProductKey string               `json:"product_key"`
	Delivered  []DeliveryItem       `json:"delivered"`
	Status     DeliveryRecordStatus `json:"status"`
}

type DeliveryError

type DeliveryError struct {
	Kind    string
	Message string
}

func (*DeliveryError) Error

func (e *DeliveryError) Error() string

type DeliveryItem

type DeliveryItem struct {
	Value string `json:"value"`
}

type DeliveryItemFormat

type DeliveryItemFormat int

DeliveryItemFormat controls how items are rendered in the delivery message.

const (
	ItemFormatPlainLines DeliveryItemFormat = iota
	ItemFormatNumbered
	ItemFormatCodeBlock
)

type DeliveryMatch

type DeliveryMatch struct {
	ProductKey string
	Items      []DeliveryItem
}

type DeliveryMessageBuilder

type DeliveryMessageBuilder struct {
	Greeting          string
	Intro             string
	ItemFormat        DeliveryItemFormat
	IncludeOrderID    bool
	IncludeProductKey bool
	Footer            string
	Template          string
	// contains filtered or unexported fields
}

func NewDeliveryMessageBuilder

func NewDeliveryMessageBuilder() *DeliveryMessageBuilder

func (*DeliveryMessageBuilder) BuildMessage

func (b *DeliveryMessageBuilder) BuildMessage(order *OrderInfo, result *DeliveryResult) string

func (*DeliveryMessageBuilder) FormatItems

func (b *DeliveryMessageBuilder) FormatItems(items []DeliveryItem) string

func (*DeliveryMessageBuilder) NoFooter

func (*DeliveryMessageBuilder) NoTemplate

func (*DeliveryMessageBuilder) SetFooter

func (*DeliveryMessageBuilder) SetGreeting

func (*DeliveryMessageBuilder) SetIncludeOrderID

func (b *DeliveryMessageBuilder) SetIncludeOrderID(v bool) *DeliveryMessageBuilder

func (*DeliveryMessageBuilder) SetIncludeProductKey

func (b *DeliveryMessageBuilder) SetIncludeProductKey(v bool) *DeliveryMessageBuilder

func (*DeliveryMessageBuilder) SetIntro

func (*DeliveryMessageBuilder) SetItemFormat

func (*DeliveryMessageBuilder) SetTemplate

type DeliveryMessenger

type DeliveryMessenger interface {
	SendDeliveryMessage(chatID, text string) (*RunnerResponse, error)
}

DeliveryMessenger sends delivery messages (interface for testability).

type DeliveryRecordStatus

type DeliveryRecordStatus string
const (
	RecordPending   DeliveryRecordStatus = "pending"
	RecordDelivered DeliveryRecordStatus = "delivered"
)

type DeliveryResult

type DeliveryResult struct {
	OrderID    string         `json:"order_id"`
	ProductKey string         `json:"product_key"`
	Delivered  []DeliveryItem `json:"delivered"`
}

type DeliveryService

type DeliveryService struct {
	Products map[string]*ProductInventory
	// contains filtered or unexported fields
}

func NewDeliveryService

func NewDeliveryService() *DeliveryService

func (*DeliveryService) AddProduct

func (s *DeliveryService) AddProduct(key string, items []DeliveryItem)

func (*DeliveryService) Deliver

func (s *DeliveryService) Deliver(matcher ProductMatcher, order *OrderInfo) (*DeliveryResult, error)

func (*DeliveryService) DeliverOrder

func (s *DeliveryService) DeliverOrder(matcher ProductMatcher, store DeliveryStore, order *OrderInfo) (*DeliveryResult, error)

DeliverOrder delivers an order with deduplication via DeliveryStore.

func (*DeliveryService) MatchOrder

func (s *DeliveryService) MatchOrder(matcher ProductMatcher, order *OrderInfo) (*DeliveryMatch, error)

func (*DeliveryService) ProcessPaidOrder

func (s *DeliveryService) ProcessPaidOrder(
	matcher ProductMatcher,
	store DeliveryStore,
	messenger DeliveryMessenger,
	builder *DeliveryMessageBuilder,
	order *OrderInfo,
) (*ProcessPaidOrderResult, error)

ProcessPaidOrder is a high-level method that matches, reserves, sends, and commits.

func (*DeliveryService) ReleaseReserved

func (s *DeliveryService) ReleaseReserved(reserved *ReservedDelivery)

func (*DeliveryService) RemainingItems

func (s *DeliveryService) RemainingItems(productKey string) int

func (*DeliveryService) Reserve

func (s *DeliveryService) Reserve(matcher ProductMatcher, order *OrderInfo) (*ReservedDelivery, error)

type DeliveryStore

type DeliveryStore interface {
	ContainsOrder(orderID string) (bool, error)
	ClaimPending(result *DeliveryResult) error
	CommitDelivered(result *DeliveryResult) error
	ReleasePending(orderID string) error
}

DeliveryStore persists delivery records to prevent duplicate deliveries.

type ErrorKind

type ErrorKind int
const (
	ErrMissingGoldenKey ErrorKind = iota
	ErrUnauthorized
	ErrHTTP
	ErrParse
	ErrIO
	ErrDelivery
	ErrState
)

type EventStream

type EventStream struct {
	SeenOrders   map[string]struct{}
	SeenMessages map[string]int64
}

EventStream tracks seen orders/messages for dedup.

func (*EventStream) ShouldEmitMessage

func (s *EventStream) ShouldEmitMessage(msg ChatMessage, filter *MessageFilter) bool

ShouldEmitMessage checks if a message is new and passes the filter.

func (*EventStream) ShouldEmitOrder

func (s *EventStream) ShouldEmitOrder(id string) bool

ShouldEmitOrder returns true if the order is new (not yet seen).

type ExactSubcategoryMatcher

type ExactSubcategoryMatcher struct{}

ExactSubcategoryMatcher matches orders where subcategory equals the product key.

func (ExactSubcategoryMatcher) Matches

func (ExactSubcategoryMatcher) Matches(productKey string, order *OrderInfo) bool

type FetchOrderOptions

type FetchOrderOptions struct {
	Status        *OrderStatus
	MinAmount     *int32
	MaxAmount     *int32
	Subcategory   *string
	BuyerID       *int64
	BuyerUsername *string
	Description   *string
}

FetchOrderOptions for client-side filtering.

type GoldenPay

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

GoldenPay is the reusable HTTP client.

func New

func New(config *GoldenPayConfig) (*GoldenPay, error)

func (*GoldenPay) Connect

func (c *GoldenPay) Connect() (*GoldenPaySession, error)

Connect authenticates via golden_key cookie and parses UserInfo.

func (*GoldenPay) ValidateProxy

func (c *GoldenPay) ValidateProxy() (bool, error)

ValidateProxy checks if the proxy (if configured) is reachable.

type GoldenPayBot

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

GoldenPayBot polls for new orders and messages.

func NewBot

func NewBot(session *GoldenPaySession) *GoldenPayBot

func (*GoldenPayBot) Bootstrap

func (b *GoldenPayBot) Bootstrap() error

Bootstrap fetches all current orders and messages to seed seen state.

func (*GoldenPayBot) LoadState

func (b *GoldenPayBot) LoadState() error

func (*GoldenPayBot) Run

func (b *GoldenPayBot) Run(ctx context.Context, handler func(GoldenPayEvent) error) error

func (*GoldenPayBot) SaveState

func (b *GoldenPayBot) SaveState() error

func (*GoldenPayBot) WithOptions

func (b *GoldenPayBot) WithOptions(opts BotOptions) *GoldenPayBot

func (*GoldenPayBot) WithStore

func (b *GoldenPayBot) WithStore(store StateStore) *GoldenPayBot

type GoldenPayConfig

type GoldenPayConfig struct {
	GoldenKey             string        `json:"golden_key"`
	BaseURL               string        `json:"base_url"`
	UserAgent             string        `json:"user_agent"`
	PollInterval          time.Duration `json:"poll_interval"`
	MaxRetries            int           `json:"max_retries"`
	RetryBaseDelay        time.Duration `json:"retry_base_delay"`
	MaxConcurrentRequests int           `json:"max_concurrent_requests"`
	Proxy                 string        `json:"proxy,omitempty"`
	StatePath             string        `json:"state_path,omitempty"`
}

GoldenPayConfig holds runtime configuration.

func DefaultConfig

func DefaultConfig() *GoldenPayConfig

func NewConfig

func NewConfig(goldenKey string) *GoldenPayConfig

func (*GoldenPayConfig) Validate

func (c *GoldenPayConfig) Validate() error

type GoldenPayError

type GoldenPayError struct {
	Kind    ErrorKind
	Message string
	Err     error
}

GoldenPayError represents SDK errors.

func (*GoldenPayError) Error

func (e *GoldenPayError) Error() string

func (*GoldenPayError) Unwrap

func (e *GoldenPayError) Unwrap() error

type GoldenPayEvent

type GoldenPayEvent struct {
	NewOrder   *OrderInfo   `json:"new_order,omitempty"`
	NewMessage *ChatMessage `json:"new_message,omitempty"`
}

GoldenPayEvent emitted by the bot.

type GoldenPaySession

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

GoldenPaySession is an authenticated session.

func (*GoldenPaySession) CalcPrice

func (s *GoldenPaySession) CalcPrice(nodeID int64, price float64) (*PriceCalculation, error)

CalcPrice calculates buyer/seller prices and commission.

func (*GoldenPaySession) CalculateStatistics

func (s *GoldenPaySession) CalculateStatistics(opts *FetchOrderOptions) (*StoreStatistics, error)

CalculateStatistics computes totals from filtered orders.

func (*GoldenPaySession) CheckConnection

func (s *GoldenPaySession) CheckConnection() bool

CheckConnection pings the home page.

func (*GoldenPaySession) Config

func (s *GoldenPaySession) Config() *GoldenPayConfig

func (*GoldenPaySession) CreateOffer

func (s *GoldenPaySession) CreateOffer(nodeID int64, details OfferEdit) (*OfferSaveResponse, error)

CreateOffer creates a new offer.

func (*GoldenPaySession) DeactivateAllOffers

func (s *GoldenPaySession) DeactivateAllOffers(nodeID int64) error

DeactivateAllOffers sets active=false for all offers in a node.

func (*GoldenPaySession) DeleteAllOffers

func (s *GoldenPaySession) DeleteAllOffers(nodeID int64) error

DeleteAllOffers deletes all offers in a category.

func (*GoldenPaySession) DeleteOffer added in v1.1.0

func (s *GoldenPaySession) DeleteOffer(nodeID, offerID int64) error

DeleteOffer deletes a specific offer by ID.

func (*GoldenPaySession) EditOffer

func (s *GoldenPaySession) EditOffer(nodeID, offerID int64, patch OfferEdit) (*OfferSaveResponse, error)

EditOffer patches an existing offer.

func (*GoldenPaySession) FetchBalance

func (s *GoldenPaySession) FetchBalance() (float64, error)

FetchBalance returns the current account balance.

func (*GoldenPaySession) FetchCategoryFilters

func (s *GoldenPaySession) FetchCategoryFilters(nodeID int64) ([]CategoryFilter, error)

FetchCategoryFilters returns filter controls from a category page.

func (*GoldenPaySession) FetchCategorySubcategories

func (s *GoldenPaySession) FetchCategorySubcategories(nodeID int64) ([]CategorySubcategory, error)

FetchCategorySubcategories returns subcategory pills from a category page.

func (*GoldenPaySession) FetchCategoryTree

func (s *GoldenPaySession) FetchCategoryTree() ([]CategoryNode, error)

FetchCategoryTree returns the full marketplace category tree.

func (*GoldenPaySession) FetchChatMessages

func (s *GoldenPaySession) FetchChatMessages(chatID string) ([]ChatMessage, error)

FetchChatMessages fetches messages from a chat.

func (*GoldenPaySession) FetchMarketOffers

func (s *GoldenPaySession) FetchMarketOffers(nodeID int64) ([]MarketOffer, error)

FetchMarketOffers returns public offers (competitors) on the market page.

func (*GoldenPaySession) FetchMyOffers

func (s *GoldenPaySession) FetchMyOffers(nodeID int64) ([]Offer, error)

FetchMyOffers returns the seller's own offers for a category node.

func (*GoldenPaySession) FetchOfferDetails

func (s *GoldenPaySession) FetchOfferDetails(nodeID, offerID int64) (*OfferDetails, error)

FetchOfferDetails returns current field values for editing.

func (*GoldenPaySession) FetchOrderPage

func (s *GoldenPaySession) FetchOrderPage(orderID string) (*OrderPage, error)

FetchOrderPage returns full order details.

func (*GoldenPaySession) FetchOrders

func (s *GoldenPaySession) FetchOrders() ([]OrderInfo, error)

FetchOrders returns all orders from the trade page.

func (*GoldenPaySession) FetchOrdersWith

func (s *GoldenPaySession) FetchOrdersWith(opts *FetchOrderOptions) ([]OrderInfo, error)

FetchOrdersWith applies client-side filters.

func (*GoldenPaySession) FetchPaidOrders

func (s *GoldenPaySession) FetchPaidOrders() ([]OrderInfo, error)

FetchPaidOrders returns only paid orders.

func (*GoldenPaySession) FetchProfileReviews

func (s *GoldenPaySession) FetchProfileReviews(userID int64) ([]ProfileReview, error)

FetchProfileReviews returns reviews from a user profile.

func (*GoldenPaySession) LeaveReview added in v1.1.0

func (s *GoldenPaySession) LeaveReview(orderID string, rating int, text string) (*RunnerResponse, error)

LeaveReview leaves a review for a buyer.

func (*GoldenPaySession) Ping

func (s *GoldenPaySession) Ping() (*RunnerResponse, error)

Ping sends a runner heartbeat.

func (*GoldenPaySession) RaiseOffers

func (s *GoldenPaySession) RaiseOffers(nodeID int64) (*RaiseOffersResponse, error)

RaiseOffers raises all offers in a category.

func (*GoldenPaySession) RefundOrder added in v1.1.0

func (s *GoldenPaySession) RefundOrder(orderID string) (*RunnerResponse, error)

RefundOrder refunds an order.

func (*GoldenPaySession) ReplyToReview

func (s *GoldenPaySession) ReplyToReview(orderID, text string) (*RunnerResponse, error)

ReplyToReview replies to an order review.

func (*GoldenPaySession) SendMessage

func (s *GoldenPaySession) SendMessage(chatID, text string) (*RunnerResponse, error)

SendMessage sends a text message to a chat.

func (*GoldenPaySession) SetGoldenKey

func (s *GoldenPaySession) SetGoldenKey(key string)

func (*GoldenPaySession) UndercutPrice

func (s *GoldenPaySession) UndercutPrice(nodeID, offerID int64, undercutBy, minPrice float64) (*OfferSaveResponse, error)

UndercutPrice sets offer price to lowest competitor minus undercut_by.

func (*GoldenPaySession) User

func (s *GoldenPaySession) User() *UserInfo

func (*GoldenPaySession) Withdraw

func (s *GoldenPaySession) Withdraw(req *WithdrawRequest) (*RunnerResponse, error)

Withdraw initiates a payout.

type JSONDeliveryStore

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

JSONDeliveryStore persists delivery records to a JSON file.

func NewJSONDeliveryStore

func NewJSONDeliveryStore(path string) *JSONDeliveryStore

func (*JSONDeliveryStore) ClaimPending

func (s *JSONDeliveryStore) ClaimPending(result *DeliveryResult) error

func (*JSONDeliveryStore) CommitDelivered

func (s *JSONDeliveryStore) CommitDelivered(result *DeliveryResult) error

func (*JSONDeliveryStore) ContainsOrder

func (s *JSONDeliveryStore) ContainsOrder(orderID string) (bool, error)

func (*JSONDeliveryStore) ReleasePending

func (s *JSONDeliveryStore) ReleasePending(orderID string) error

type JSONStateStore

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

JSONStateStore persists state to a JSON file.

func NewJSONStateStore

func NewJSONStateStore(path string) *JSONStateStore

func (*JSONStateStore) Load

func (s *JSONStateStore) Load() (*BotState, error)

func (*JSONStateStore) Save

func (s *JSONStateStore) Save(state *BotState) error

type MarketOffer

type MarketOffer struct {
	ID            int64   `json:"id"`
	NodeID        int64   `json:"node_id"`
	Description   string  `json:"description"`
	Price         float64 `json:"price"`
	Currency      string  `json:"currency"`
	SellerID      int64   `json:"seller_id"`
	SellerName    string  `json:"seller_name"`
	SellerOnline  bool    `json:"seller_online"`
	SellerRating  float64 `json:"seller_rating"`
	SellerReviews int32   `json:"seller_reviews"`
	IsPromo       bool    `json:"is_promo"`
}

MarketOffer is a public offer on the market page.

type MemoryDeliveryStore

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

MemoryDeliveryStore is an in-memory delivery store.

func NewMemoryDeliveryStore

func NewMemoryDeliveryStore() *MemoryDeliveryStore

func (*MemoryDeliveryStore) ClaimPending

func (s *MemoryDeliveryStore) ClaimPending(result *DeliveryResult) error

func (*MemoryDeliveryStore) CommitDelivered

func (s *MemoryDeliveryStore) CommitDelivered(result *DeliveryResult) error

func (*MemoryDeliveryStore) ContainsOrder

func (s *MemoryDeliveryStore) ContainsOrder(orderID string) (bool, error)

func (*MemoryDeliveryStore) ReleasePending

func (s *MemoryDeliveryStore) ReleasePending(orderID string) error

type MemoryStateStore

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

MemoryStateStore is an in-memory store (non-persistent).

func NewMemoryStateStore

func NewMemoryStateStore() *MemoryStateStore

func (*MemoryStateStore) Load

func (s *MemoryStateStore) Load() (*BotState, error)

func (*MemoryStateStore) Save

func (s *MemoryStateStore) Save(state *BotState) error

type MessageFilter

type MessageFilter struct {
	IgnoreAuthorID int64
	MinMessageID   int64
}

MessageFilter for filtering chat messages.

type NewMessageWebhook added in v1.1.0

type NewMessageWebhook struct {
	ChatID string `json:"chat_id"`
	Text   string `json:"text,omitempty"`
}

type NewOrderWebhook added in v1.1.0

type NewOrderWebhook struct {
	ID     string  `json:"id"`
	Amount float64 `json:"amount,omitempty"`
}

type Offer

type Offer struct {
	ID          int64   `json:"id"`
	NodeID      int64   `json:"node_id"`
	Description string  `json:"description"`
	Price       float64 `json:"price"`
	Currency    string  `json:"currency"`
	Active      bool    `json:"active"`
}

Offer is a seller's own offer on the trade page.

type OfferDetails

type OfferDetails struct {
	Current      OfferEdit    `json:"current"`
	CustomFields []OfferField `json:"custom_fields"`
}

OfferDetails is the current state of an offer from the edit page.

type OfferEdit

type OfferEdit struct {
	Quantity            *string `json:"quantity,omitempty"`
	Quantity2           *string `json:"quantity2,omitempty"`
	Method              *string `json:"method,omitempty"`
	OfferType           *string `json:"offer_type,omitempty"`
	ServerID            *string `json:"server_id,omitempty"`
	Location            *string `json:"location,omitempty"`
	Price               *string `json:"price,omitempty"`
	Active              *bool   `json:"active,omitempty"`
	Deleted             *bool   `json:"deleted,omitempty"`
	DescriptionRU       *string `json:"desc_ru,omitempty"`
	DescriptionEN       *string `json:"desc_en,omitempty"`
	PaymentMsgRU        *string `json:"payment_msg_ru,omitempty"`
	PaymentMsgEN        *string `json:"payment_msg_en,omitempty"`
	SummaryRU           *string `json:"summary_ru,omitempty"`
	SummaryEN           *string `json:"summary_en,omitempty"`
	Game                *string `json:"game,omitempty"`
	Images              *string `json:"images,omitempty"`
	DeactivateAfterSale *bool   `json:"deactivate_after_sale,omitempty"`
}

OfferEdit patches or creates an offer.

func (OfferEdit) Merge

func (e OfferEdit) Merge(other OfferEdit) OfferEdit

Merge returns a new OfferEdit with non-nil fields from other overriding.

type OfferEditBuilder

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

OfferEditBuilder provides a fluent API for building OfferEdit patches.

func NewOfferEditBuilder

func NewOfferEditBuilder() *OfferEditBuilder

func (*OfferEditBuilder) Active

func (b *OfferEditBuilder) Active(v bool) *OfferEditBuilder

func (*OfferEditBuilder) Build

func (b *OfferEditBuilder) Build() OfferEdit

Build returns the constructed OfferEdit.

func (*OfferEditBuilder) DeactivateAfterSale

func (b *OfferEditBuilder) DeactivateAfterSale(v bool) *OfferEditBuilder

func (*OfferEditBuilder) Deleted

func (b *OfferEditBuilder) Deleted(v bool) *OfferEditBuilder

func (*OfferEditBuilder) DescEN

func (*OfferEditBuilder) DescRU

func (*OfferEditBuilder) Game

func (*OfferEditBuilder) Images

func (*OfferEditBuilder) Location

func (b *OfferEditBuilder) Location(v string) *OfferEditBuilder

func (*OfferEditBuilder) Method

func (*OfferEditBuilder) OfferType

func (b *OfferEditBuilder) OfferType(v string) *OfferEditBuilder

func (*OfferEditBuilder) PaymentMsgEN

func (b *OfferEditBuilder) PaymentMsgEN(v string) *OfferEditBuilder

func (*OfferEditBuilder) PaymentMsgRU

func (b *OfferEditBuilder) PaymentMsgRU(v string) *OfferEditBuilder

func (*OfferEditBuilder) Price

func (*OfferEditBuilder) Quantity

func (b *OfferEditBuilder) Quantity(v string) *OfferEditBuilder

func (*OfferEditBuilder) Quantity2

func (b *OfferEditBuilder) Quantity2(v string) *OfferEditBuilder

func (*OfferEditBuilder) ServerID

func (b *OfferEditBuilder) ServerID(v string) *OfferEditBuilder

func (*OfferEditBuilder) SummaryEN

func (b *OfferEditBuilder) SummaryEN(v string) *OfferEditBuilder

func (*OfferEditBuilder) SummaryRU

func (b *OfferEditBuilder) SummaryRU(v string) *OfferEditBuilder

type OfferField

type OfferField struct {
	Name      string `json:"name"`
	Label     string `json:"label"`
	FieldType string `json:"field_type"` // input, textarea, select
	Value     string `json:"value"`
	Required  bool   `json:"required"`
}

OfferField is a dynamic custom field in the offer edit form.

type OfferGroup

type OfferGroup struct {
	NodeID     int64
	ActiveOnly bool
}

OfferGroup defines a group of offers to manage.

func NewOfferGroup

func NewOfferGroup(nodeID int64, activeOnly bool) OfferGroup

type OfferSaveResponse

type OfferSaveResponse struct {
	Success bool   `json:"success"`
	Error   string `json:"error,omitempty"`
}

OfferSaveResponse after editing/creating an offer.

type OfferScheduler

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

OfferScheduler evaluates entries and reports transitions.

func NewOfferScheduler

func NewOfferScheduler(entries []ScheduleEntry) *OfferScheduler

func (*OfferScheduler) Poll

func (s *OfferScheduler) Poll(now time.Time) []Transition

type OrderInfo

type OrderInfo struct {
	ID              string      `json:"id"`
	BuyerUsername   string      `json:"buyer_username"`
	BuyerID         int64       `json:"buyer_id"`
	ChatID          string      `json:"chat_id"`
	Description     string      `json:"description"`
	SubcategoryName string      `json:"subcategory_name"`
	Amount          int32       `json:"amount"`
	Status          OrderStatus `json:"status"`
}

OrderInfo is a compact order from the trade page.

type OrderPage

type OrderPage struct {
	ID              string      `json:"id"`
	Status          OrderStatus `json:"status"`
	Amount          int32       `json:"amount"`
	Sum             float64     `json:"sum"`
	Currency        string      `json:"currency"`
	BuyerID         int64       `json:"buyer_id"`
	BuyerUsername   string      `json:"buyer_username"`
	ChatID          string      `json:"chat_id"`
	ShortDesc       string      `json:"short_description,omitempty"`
	FullDesc        string      `json:"full_description,omitempty"`
	SubcategoryName string      `json:"subcategory_name,omitempty"`
	Secrets         []string    `json:"secrets"`
	Params          [][2]string `json:"params"`
	Review          *Review     `json:"review,omitempty"`
	RawHTML         string      `json:"raw_html"`
}

OrderPage is a detailed order with secrets and review.

type OrderStatus

type OrderStatus string
const (
	OrderPaid     OrderStatus = "paid"
	OrderClosed   OrderStatus = "closed"
	OrderRefunded OrderStatus = "refunded"
)

type PriceCalculation

type PriceCalculation struct {
	InputPrice    float64            `json:"input_price"`
	SellerPrice   *float64           `json:"seller_price,omitempty"`
	BuyerPrice    *float64           `json:"buyer_price,omitempty"`
	Commission    *float64           `json:"commission,omitempty"`
	NumericFields map[string]float64 `json:"numeric_fields"`
}

PriceCalculation holds price breakdown.

type ProcessPaidOrderResult

type ProcessPaidOrderResult struct {
	Delivery       *DeliveryResult
	MessageText    string
	RunnerResponse *RunnerResponse
}

ProcessPaidOrderResult holds the outcome of ProcessPaidOrder.

type ProductInventory

type ProductInventory struct {
	Items []DeliveryItem
}

type ProductMatcher

type ProductMatcher interface {
	Matches(productKey string, order *OrderInfo) bool
}

ProductMatcher determines whether a product matches an order.

type ProfileReview

type ProfileReview struct {
	BuyerUsername string `json:"buyer_username"`
	BuyerID       int64  `json:"buyer_id"`
	Stars         int    `json:"stars"`
	Text          string `json:"text"`
	OrderID       string `json:"order_id"`
}

ProfileReview from a user profile page.

type RaiseOffersResponse

type RaiseOffersResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message,omitempty"`
}

type ReservedDelivery

type ReservedDelivery struct {
	Result DeliveryResult
}

type Review

type Review struct {
	Stars int    `json:"stars"`
	Text  string `json:"text,omitempty"`
}

type RunnerObject

type RunnerObject struct {
	Type string          `json:"type"`
	ID   string          `json:"id"`
	Data json.RawMessage `json:"data"`
}

RunnerObject is a typed object from the runner response.

type RunnerResponse

type RunnerResponse struct {
	Success      bool           `json:"success"`
	ErrorMessage string         `json:"error_message,omitempty"`
	Objects      []RunnerObject `json:"objects"`
}

RunnerResponse from the /runner/ endpoint.

type ScheduleAction

type ScheduleAction int

ScheduleAction is what to do with offers.

const (
	ActionActivate ScheduleAction = iota
	ActionDeactivate
)

func (ScheduleAction) DesiredActive

func (a ScheduleAction) DesiredActive() bool

type ScheduleEntry

type ScheduleEntry struct {
	Name   string
	Group  OfferGroup
	Rule   ScheduleRule
	Action ScheduleAction
}

ScheduleEntry binds a group, rule, and action.

func NewScheduleEntry

func NewScheduleEntry(name string, group OfferGroup, rule ScheduleRule, action ScheduleAction) ScheduleEntry

type ScheduleRule

type ScheduleRule struct {
	StartHour int // 0-23
	EndHour   int // 0-23
}

ScheduleRule defines when to apply an action.

func NewScheduleRule

func NewScheduleRule(start, end int) ScheduleRule

func (ScheduleRule) IsActive

func (r ScheduleRule) IsActive(now time.Time) bool

type SecureString

type SecureString string

SecureString masks its value in string output (always returns "***").

func NewSecureString

func NewSecureString(s string) SecureString

func (SecureString) GoString

func (s SecureString) GoString() string

func (SecureString) String

func (s SecureString) String() string

func (SecureString) Value

func (s SecureString) Value() string

type SessionManager

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

SessionManager wraps GoldenPaySession with auto-reconnect on auth errors.

func NewSessionManager

func NewSessionManager(client *GoldenPay) *SessionManager

func (*SessionManager) EditOffer

func (m *SessionManager) EditOffer(nodeID, offerID int64, patch OfferEdit) (*OfferSaveResponse, error)

func (*SessionManager) FetchBalance

func (m *SessionManager) FetchBalance() (float64, error)

func (*SessionManager) FetchChatMessages

func (m *SessionManager) FetchChatMessages(chatID string) ([]ChatMessage, error)

func (*SessionManager) FetchMyOffers

func (m *SessionManager) FetchMyOffers(nodeID int64) ([]Offer, error)

func (*SessionManager) FetchOrderPage

func (m *SessionManager) FetchOrderPage(id string) (*OrderPage, error)

func (*SessionManager) FetchOrders

func (m *SessionManager) FetchOrders() ([]OrderInfo, error)

func (*SessionManager) FetchPaidOrders

func (m *SessionManager) FetchPaidOrders() ([]OrderInfo, error)

func (*SessionManager) Ping

func (m *SessionManager) Ping() (*RunnerResponse, error)

func (*SessionManager) SendMessage

func (m *SessionManager) SendMessage(chatID, text string) (*RunnerResponse, error)

func (*SessionManager) Session

func (m *SessionManager) Session() *GoldenPaySession

func (*SessionManager) Start

func (m *SessionManager) Start() error

type SessionMessenger

type SessionMessenger struct {
	Session *GoldenPaySession
}

SessionMessenger adapts GoldenPaySession to DeliveryMessenger.

func (*SessionMessenger) SendDeliveryMessage

func (m *SessionMessenger) SendDeliveryMessage(chatID, text string) (*RunnerResponse, error)

type StateStore

type StateStore interface {
	Load() (*BotState, error)
	Save(state *BotState) error
}

StateStore persists bot state.

type StoreStatistics

type StoreStatistics struct {
	TotalRevenue   float64
	TotalSum       float64
	OrderCount     int
	UniqueBuyers   int
	BuyerUsernames []string
}

StoreStatistics computed from fetched orders.

type Transition

type Transition struct {
	Entry          *ScheduleEntry
	ShouldBeActive bool
}

type Urls

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

Urls builds API URLs.

func NewUrls

func NewUrls(base string) *Urls

func (*Urls) Base

func (u *Urls) Base() string

func (*Urls) ChatUpload

func (u *Urls) ChatUpload() string

func (*Urls) Home

func (u *Urls) Home() string

func (*Urls) LotsCalc

func (u *Urls) LotsCalc() string

func (*Urls) LotsHome

func (u *Urls) LotsHome() string

func (*Urls) LotsPage

func (u *Urls) LotsPage(nodeID int64) string

func (*Urls) LotsRaise

func (u *Urls) LotsRaise() string

func (*Urls) LotsTrade

func (u *Urls) LotsTrade(nodeID int64) string

func (*Urls) OfferEdit

func (u *Urls) OfferEdit(nodeID, offerID int64) string

func (*Urls) OfferSave

func (u *Urls) OfferSave() string

func (*Urls) OrderPage

func (u *Urls) OrderPage(id string) string

func (*Urls) OrderReview added in v1.1.0

func (u *Urls) OrderReview() string

func (*Urls) OrdersRefund added in v1.1.0

func (u *Urls) OrdersRefund() string

func (*Urls) OrdersTrade

func (u *Urls) OrdersTrade() string

func (*Urls) Profile

func (u *Urls) Profile(userID int64) string

func (*Urls) ReviewReply

func (u *Urls) ReviewReply() string

func (*Urls) Runner

func (u *Urls) Runner() string

func (*Urls) Withdraw

func (u *Urls) Withdraw() string

type UserInfo

type UserInfo struct {
	ID        int64  `json:"id"`
	Username  string `json:"username"`
	CSRFToken string `json:"csrf_token"`
	PHPSessID string `json:"phpsessid,omitempty"`
}

UserInfo holds authenticated user metadata.

type WebhookConfig

type WebhookConfig struct {
	BindAddr    string // e.g. "127.0.0.1:9090"
	Endpoint    string // e.g. "/webhook"
	Secret      string // HMAC secret (empty = disabled)
	MaxBodySize int64
}

WebhookConfig for the notification server.

func DefaultWebhookConfig

func DefaultWebhookConfig() *WebhookConfig

type WebhookEvent added in v1.1.0

type WebhookEvent struct {
	Type    WebhookEventType
	Payload WebhookPayload

	NewOrder   *NewOrderWebhook
	NewMessage *NewMessageWebhook
}

WebhookEvent represents a parsed webhook event.

type WebhookEventType added in v1.1.0

type WebhookEventType string
const (
	EventNewOrder   WebhookEventType = "new_order"
	EventNewMessage WebhookEventType = "new_message"
	EventRaw        WebhookEventType = "raw"
)

type WebhookHandler

type WebhookHandler interface {
	HandleWebhook(event WebhookEvent) error
}

WebhookHandler processes incoming webhook events.

type WebhookPayload

type WebhookPayload struct {
	SourceIP string
	Body     json.RawMessage
	Headers  map[string]string
}

WebhookPayload carries the raw request context.

type WebhookServer

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

WebhookServer receives POST notifications.

func NewWebhookServer

func NewWebhookServer(config *WebhookConfig, handler WebhookHandler) *WebhookServer

func (*WebhookServer) Run

func (s *WebhookServer) Run() error

type WithdrawRequest

type WithdrawRequest struct {
	Currency    string  `json:"currency"`
	ExtCurrency string  `json:"ext_currency"`
	Wallet      string  `json:"wallet"`
	Amount      float64 `json:"amount"`
}

WithdrawRequest initiates a payout.

Directories

Path Synopsis
cmd
example command
Example demonstrates basic goldenpay-go usage.
Example demonstrates basic goldenpay-go usage.
webhook_bot command

Jump to

Keyboard shortcuts

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