tinkoff

package module
v0.0.0-...-387070d Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2019 License: Apache-2.0 Imports: 11 Imported by: 0

README

Go client for Tinkoff Acquiring API (v2)

API Docs: https://oplata.tinkoff.ru/landing/develop/documentation

Based on some code from nikita-vanyasin/tinkoff

Differences:
  • more implemented methods
  • go modules
Currently implemented features:

Installation

go get github.com/codex-team/tinkoff.api.golang

Usage example

Create and initialize client with API credentials:
client := tinkoff.NewClient(terminalKey, terminalPassword)
Send Init request:
req := &tinkoff.InitRequest{
    Amount:      60000,
    OrderID:     "123456",
    CustomerKey: "123",
    Description: "some really useful product",
    Receipt: tinkoff.Receipt{
        Email: "user@example.com",
        Items: []*tinkoff.ReceiptItem{
            {
                Price:    60000,
                Quantity: "1",
                Amount:   60000,
                Name:     "Product #1",
                Tax:      tinkoff.VATNone,
            },
        },
        Taxation: tinkoff.TaxationUSNIncome,
    },
    Data: map[string]string{
        "custom data field 1": "aasd6da78dasd9",
        "custom data field 2": "0",
    },
}
status, paymentID, paymentURL, err := a.client.Init(req)
Handle HTTP-notification (example using gin):
router.POST("/payment/notification/tinkoff", func(c *gin.Context) {
    notification, err := a.client.ParseNotification(c.Request.Body)
    if err != nil {
        handleInternalError(c, err)
        return
    }
    
    c.String(http.StatusOK, a.client.GetNotificationSuccessResponse())
}
Cancel (refund) (example using gin):
status, originalAmount, newAmount, err := a.client.Cancel(req)

Documentation

Index

Constants

View Source
const (
	TaxationOSN              = "osn"                // общая СН
	TaxationUSNIncome        = "usn_income"         // упрощенная СН (доходы)
	TaxationUSNIncomeOutcome = "usn_income_outcome" // упрощенная СН (доходы минус расходы)
	TaxationENVD             = "envd"               // единый налог на вмененный доход
	TaxationESN              = "esn"                // единый сельскохозяйственный налог
	TaxationPatent           = "patent"             // патентная СН
)
View Source
const (
	VATNone = "none"   // без НДС
	VAT0    = "vat0"   // НДС по ставке 0%
	VAT10   = "vat10"  // НДС чека по ставке 10%
	VAT18   = "vat18"  // НДС чека по ставке 18%
	VAT110  = "vat110" // НДС чека по расчетной ставке 10/110
	VAT118  = "vat118" // НДС чека по расчетной ставке 18/118
)
View Source
const (
	StatusNew             = "NEW"
	StatusAuthorized      = "AUTHORIZED"       // Деньги захолдированы на карте клиента. Ожидается подтверждение операции
	StatusConfirmed       = "CONFIRMED"        // Операция подтверждена
	StatusReversed        = "REVERSED"         // Операция отменена
	StatusRefunded        = "REFUNDED"         // Произведён возврат
	StatusPartialRefunded = "PARTIAL_REFUNDED" // Произведён частичный возврат
	StatusRejected        = "REJECTED"         // Списание денежных средств закончилась ошибкой
)
View Source
const (
	RedirectDueDateFormat = time.RFC3339
)

Variables

This section is empty.

Functions

func IsRefundableStatus

func IsRefundableStatus(status string) bool

Types

type BaseRequest

type BaseRequest struct {
	TerminalKey string `json:"TerminalKey"`
	Token       string `json:"Token"`
}

func (*BaseRequest) SetTerminalKey

func (r *BaseRequest) SetTerminalKey(key string)

func (*BaseRequest) SetToken

func (r *BaseRequest) SetToken(token string)

type CancelRequest

type CancelRequest struct {
	BaseRequest

	PaymentID uint64   `json:"PaymentId"`
	ClientIP  string   `json:"IP"`
	Amount    uint64   `json:"Amount"`
	Receipt   *Receipt `json:"Receipt"`
}

func (*CancelRequest) GetValuesForToken

func (i *CancelRequest) GetValuesForToken() map[string]string

type CancelResponse

type CancelResponse struct {
	TerminalKey    string `json:"TerminalKey"`       // Идентификатор терминала, выдается Продавцу Банком
	OriginalAmount uint64 `json:"OriginalAmount"`    // Сумма в копейках до операции отмены
	NewAmount      uint64 `json:"NewAmount"`         // Сумма в копейках после операции отмены
	OrderID        string `json:"OrderId"`           // Номер заказа в системе Продавца
	Success        bool   `json:"Success"`           // Успешность операции
	Status         string `json:"Status"`            // Статус транзакции
	PaymentID      string `json:"PaymentId"`         // Уникальный идентификатор транзакции в системе Банка
	ErrorCode      string `json:"ErrorCode"`         // Код ошибки, «0» - если успешно
	ErrorMessage   string `json:"Message,omitempty"` // Краткое описание ошибки
	ErrorDetails   string `json:"Details,omitempty"` // Подробное описание ошибки
}

type Client

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

func NewClient

func NewClient(terminalKey, password string) *Client

func (*Client) Cancel

func (c *Client) Cancel(request *CancelRequest) (status string, originalAmount uint64, newAmount uint64, err error)

func (*Client) Confirm

func (c *Client) Confirm(request *ConfirmRequest) (ConfirmResponse, error)

func (*Client) GetNotificationSuccessResponse

func (c *Client) GetNotificationSuccessResponse() string

func (*Client) Init

func (c *Client) Init(request *InitRequest) (status string, paymentID uint64, paymentURL string, err error)

func (*Client) ParseNotification

func (c *Client) ParseNotification(requestBody io.Reader) (*Notification, error)

type ConfirmRequest

type ConfirmRequest struct {
	BaseRequest

	PaymentID uint64   `json:"PaymentId"`
	ClientIP  string   `json:"IP"`
	Amount    uint64   `json:"Amount"`
	Receipt   *Receipt `json:"Receipt"`
}

func (*ConfirmRequest) GetValuesForToken

func (i *ConfirmRequest) GetValuesForToken() map[string]string

type ConfirmResponse

type ConfirmResponse struct {
	TerminalKey  string `json:"TerminalKey"`       // Идентификатор терминала, выдается Продавцу Банком
	OrderID      string `json:"OrderId"`           // Номер заказа в системе Продавца
	Success      bool   `json:"Success"`           // Успешность операции
	Status       string `json:"Status"`            // Статус транзакции
	PaymentID    string `json:"PaymentId"`         // Уникальный идентификатор транзакции в системе Банка
	ErrorCode    string `json:"ErrorCode"`         // Код ошибки, «0» - если успешно
	ErrorMessage string `json:"Message,omitempty"` // Краткое описание ошибки
	ErrorDetails string `json:"Details,omitempty"` // Подробное описание ошибки
}

type InitRequest

type InitRequest struct {
	BaseRequest

	Amount          uint64            `json:"Amount"`
	OrderID         string            `json:"OrderId"`
	ClientIP        string            `json:"IP"`
	Description     string            `json:"Description"`
	CustomerKey     string            `json:"CustomerKey"`
	Data            map[string]string `json:"DATA"`
	Receipt         *Receipt          `json:"Receipt"`
	RedirectDueDate string            `json:"RedirectDueDate"`
}

func (*InitRequest) GetValuesForToken

func (i *InitRequest) GetValuesForToken() map[string]string

type InitResponse

type InitResponse struct {
	TerminalKey  string `json:"TerminalKey"`          // Идентификатор терминала, выдается Продавцу Банком
	Amount       uint64 `json:"Amount"`               // Сумма в копейках
	OrderID      string `json:"OrderId"`              // Номер заказа в системе Продавца
	Success      bool   `json:"Success"`              // Успешность операции
	Status       string `json:"Status"`               // Статус транзакции
	PaymentID    string `json:"PaymentId"`            // Уникальный идентификатор транзакции в системе Банка
	PaymentURL   string `json:"PaymentURL,omitempty"` // Ссылка на страницу оплаты. По умолчанию ссылка доступна в течении 24 часов.
	ErrorCode    string `json:"ErrorCode"`            // Код ошибки, «0» - если успешно
	ErrorMessage string `json:"Message,omitempty"`    // Краткое описание ошибки
	ErrorDetails string `json:"Details,omitempty"`    // Подробное описание ошибки
}

type Notification

type Notification struct {
	TerminalKey    string            `json:"TerminalKey"` // Идентификатор магазина
	OrderID        string            `json:"OrderId"`     // Номер заказа в системе Продавца
	Success        bool              `json:"Success"`     // Успешность операции
	Status         string            `json:"Status"`      // Статус платежа (см. описание статусов операций)
	PaymentID      uint64            `json:"PaymentId"`   // Уникальный идентификатор платежа
	ErrorCode      string            `json:"ErrorCode"`   // Код ошибки, если произошла ошибка
	Amount         uint64            `json:"Amount"`      // Текущая сумма транзакции в копейках
	RebillID       string            `json:"RebillId"`    // Идентификатор рекуррентного платежа
	CardID         uint64            `json:"CardId"`      // Идентификатор привязанной карты
	PAN            string            `json:"Pan"`         // Маскированный номер карты
	DataStr        string            `json:"DATA"`
	Data           map[string]string `json:"-"`       // Дополнительные параметры платежа, переданные при создании заказа
	Token          string            `json:"Token"`   // Подпись запроса
	ExpirationDate string            `json:"ExpDate"` // Срок действия карты
}

func (*Notification) GetValuesForToken

func (n *Notification) GetValuesForToken() map[string]string

type Receipt

type Receipt struct {
	Items    []*ReceiptItem
	Email    string
	Phone    string
	Taxation string
}

func (*Receipt) IsValid

func (r *Receipt) IsValid() bool

type ReceiptItem

type ReceiptItem struct {
	Name     string // Наименование товара. Максимальная длина строки – 64 символа
	Price    uint64 // Цена в копейках. *Целочисленное значение не более 10 знаков
	Quantity string // Количество/вес: целая часть не более 8 знаков; дробная часть не более 3 знаков
	Amount   uint64 // Сумма в копейках. Целочисленное значение не более 10 знаков
	Tax      string // Ставка налога
	Ean13    string // Штрих-код
	ShopCode string // Код магазина
}

func (*ReceiptItem) IsValid

func (i *ReceiptItem) IsValid() bool

type RequestInterface

type RequestInterface interface {
	GetValuesForToken() map[string]string
	SetTerminalKey(key string)
	SetToken(token string)
}

Jump to

Keyboard shortcuts

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