dpay

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

README

dpay Go SDK

Oficjalna biblioteka Go do integracji z API płatności dpay.pl.

Wymagania

  • Go 1.22 lub nowszy
  • Zero zależności runtime - wyłącznie biblioteka standardowa

Instalacja

go get github.com/dpayglobal/dpay-go-sdk

Szybki start

import dpay "github.com/dpayglobal/dpay-go-sdk"

client, err := dpay.New("nazwa_serwisu", "twoj_secret_hash")
if err != nil {
    return err
}

payment, err := client.Payments.Register(ctx, &dpay.RegisterPaymentRequest{
    Amount:          dpay.PLN(1050),
    TransactionType: dpay.TransactionTypeTransfers,
    URLs: dpay.ReturnURLs{
        Success: "https://twojsklep.pl/sukces",
        Fail:    "https://twojsklep.pl/blad",
        IPN:     "https://twojsklep.pl/ipn",
    },
    Description: dpay.String("Zamówienie #1234"),
    Custom:      dpay.String("order-1234"),
})
if err != nil {
    return err
}

if url := payment.RedirectURL(); url != "" {
    http.Redirect(w, r, url, http.StatusSeeOther)
}

Pola opcjonalne są wskaźnikami. nil pomija pole, a dpay.Bool(false) wysyła false - to rozróżnienie ma znaczenie dla API. Do budowania wskaźników służą dpay.String, dpay.Bool, dpay.Int i dpay.Int64.

Obsługa IPN

dpay.pl uznaje IPN za dostarczony wyłącznie, gdy body odpowiedzi to dokładnie OK. Kod HTTP nie jest sprawdzany. Zawsze weryfikuj kwotę z własnym zamówieniem.

func ipnHandler(w http.ResponseWriter, r *http.Request) {
    body, err := io.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "cannot read body", http.StatusBadRequest)
        return
    }

    event, err := dpay.VerifyIPN(body, "twoj_secret_hash")
    if err != nil {
        http.Error(w, "invalid signature", http.StatusBadRequest)
        return
    }

    if event.IsTransfer() || event.IsCapture() {
        markOrderAsPaid(event.ID(), event.Amount())
    }

    fmt.Fprint(w, dpay.IPNAck)
}

event.Amount() to surowy string dziesiętny - payload IPN nie niesie waluty, więc porównaj go z kwotą własnego zamówienia.

Zwroty

client.Refunds.Create(ctx, "identyfikator-transakcji")
client.Refunds.Create(ctx, "identyfikator-transakcji",
    dpay.WithRefundAmount(dpay.PLN(500)),
    dpay.WithRefundReason("reklamacja"))

availability, err := client.Refunds.CheckAvailability(ctx, "identyfikator-transakcji")
if err == nil && availability.IsAvailable() {
    // ...
}

Szczegóły transakcji i banki

transaction, err := client.Payments.Details(ctx, "identyfikator-transakcji")
transaction.IsPaid()
transaction.AvailableRefundAmount().String()
transaction.Refunds()

banks, err := client.Banks.ForService(ctx)

Karty S2S

publicKey, err := client.Cards.PublicKey(ctx)
encrypted, err := dpay.EncryptCard(
    dpay.CardData{PAN: "4111111111111111", CVV: "123", Expiry: "12/28"},
    transactionID,
    publicKey,
)

result, err := client.Cards.PayOTP(ctx, transactionID, &dpay.CardPaymentRequest{
    DeviceInfo:        deviceInfo,
    EncryptedCardData: dpay.String(encrypted),
})

switch {
case result.RequiresThreeDSForm():
    fmt.Fprint(w, result.ThreeDSFormHTML())
case result.RequiresRedirect():
    http.Redirect(w, r, result.RedirectURL(), http.StatusSeeOther)
case result.HasDCCOffer():
    offer := result.DCCOffer()
    _ = offer.DeclarationText()
}

Klucz publiczny jest rotowany - pobieraj go przed każdą próbą płatności, nie buforuj.

Capture pełnej kwoty wykonuje się przekazując nil:

client.Cards.Capture(ctx, transactionID, nil)
client.Cards.Capture(ctx, transactionID, &amount)

Obsługa błędów

Rodzaj błędu rozpoznaje się przez errors.Is, a szczegóły przez errors.As.

payment, err := client.Payments.Register(ctx, request)

switch {
case errors.Is(err, dpay.ErrInvalidRequest):
    var apiErr *dpay.APIError
    errors.As(err, &apiErr)
    log.Print(apiErr.FieldErrors)

case errors.Is(err, dpay.ErrPaymentRejected):
    var rejected *dpay.PaymentRejectedError
    errors.As(err, &rejected)
    log.Print(rejected.TransactionID, rejected.ErrorCode)

case errors.Is(err, dpay.ErrTransport):
    // błąd sieci - status płatności nieznany, użyj Payments.Details
}
Sentinel Kiedy
ErrAuthentication 401 - niepoprawny checksum
ErrInvalidRequest 400, 422
ErrAccessDenied 403
ErrNotFound 404
ErrRateLimit 429, *RateLimitError niesie RetryAfter
ErrServer 5xx
ErrPaymentRejected rejestracja odrzucona przy HTTP 200
ErrCardPayment płatność kartą odrzucona przy HTTP 200
ErrSignature niepoprawny podpis IPN
ErrTransport awaria sieci
ErrInvalidArgument niepoprawny argument lub pole żądania
ErrAPI pasuje do każdego błędu zwróconego przez API

Konfiguracja

Opcja Typ Opis
dpay.New(service, secretHash) string, string Nazwa Punktu Płatności z panel.dpay.pl i Secret Hash (wymagane)
WithTimeout time.Duration Timeout domyślnego klienta HTTP (domyślnie 30 s)
WithHTTPClient HTTPDoer Własny transport - proxy, retry, instrumentacja, testy
WithBaseURLs BaseURLs Nadpisanie hostów API

HTTPDoer to jednometodowy interfejs Do(*http.Request) (*http.Response, error), który *http.Client spełnia bez adaptera. Retry i timeouty per żądanie konfiguruje się własnym http.Client lub RoundTripper. Anulowanie przez context.Context działa w każdej metodzie.

Domyślny klient nie podąża za przekierowaniami - odpowiedź 302 jest zwracana jako wynik, a nie zamieniana na stronę, pod którą prowadzi. Klient płatniczy nie powinien ponawiać żądania pod adres wskazany przez odpowiedź, a dodatkowo tak zachowuje się SDK PHP, więc statusy błędów są w obu takie same. Jeśli podajesz własny *http.Client, ustaw to samo:

client, err := dpay.New("nazwa_serwisu", "twoj_secret_hash",
    dpay.WithHTTPClient(&http.Client{
        Timeout: 30 * time.Second,
        CheckRedirect: func(*http.Request, []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }))

Testowanie integracji

SDK nie dostarcza własnego mocka - wystarczy httptest z biblioteki standardowej:

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(`{"transactionId":"tx-1","msg":"https://secure.dpay.pl/pay/1"}`))
}))
defer server.Close()

client, _ := dpay.New("test", "test", dpay.WithBaseURLs(dpay.BaseURLs{
    APIPayments: server.URL,
    Panel:       server.URL,
}))

Jeśli wolisz sprawdzać wysłane żądania bez podnoszenia serwera, zaimplementuj dpay.HTTPDoer - to jednometodowy interfejs, który spełnia też *http.Client.

Zgodność z SDK PHP

To SDK jest portem dpayglobal/dpay-php-sdk i utrzymuje parytet na poziomie wire-protocol: te same ścieżki, ta sama kolejność pól w body, te same checksumy i podpisy IPN. Parytet jest mierzony, nie deklarowany - testy porównują żądania bajt w bajt z wektorami wygenerowanymi z żywego SDK PHP.

Licencja

Apache-2.0

Documentation

Overview

Package dpay is the official Go SDK for the dpay.pl payments API.

Create a client with the payment point name and secret hash from panel.dpay.pl, then use one of its six services:

client, err := dpay.New("my_shop", "secret_hash")
payment, err := client.Payments.Register(ctx, request)

Optional request fields are pointers: nil omits the field, while dpay.Bool(false) sends false explicitly. Use dpay.String, dpay.Bool, dpay.Int and dpay.Int64 to build them.

Errors are classified with errors.Is against the package sentinels and inspected with errors.As on *APIError. A *TransportError means the request never reached the API, so the payment status is unknown.

The order of fields in a request body is part of the protocol: the checksum is computed from the values in the order they are sent.

Index

Examples

Constants

View Source
const IPNAck = "OK"

IPNAck is the exact body dpay expects in an IPN response. The HTTP status is ignored: anything other than this body is treated as a failed delivery.

View Source
const Version = "0.1.0"

Version is the SDK version reported in the User-Agent header.

Variables

View Source
var (
	ErrAPI             = errors.New("dpay: API error")
	ErrAuthentication  = errors.New("dpay: authentication failed")
	ErrInvalidRequest  = errors.New("dpay: invalid request")
	ErrAccessDenied    = errors.New("dpay: access denied")
	ErrNotFound        = errors.New("dpay: not found")
	ErrRateLimit       = errors.New("dpay: rate limited")
	ErrServer          = errors.New("dpay: server error")
	ErrPaymentRejected = errors.New("dpay: payment rejected")
	ErrCardPayment     = errors.New("dpay: card payment failed")
	ErrTransport       = errors.New("dpay: transport failure")
	ErrSignature       = errors.New("dpay: signature verification failed")
	ErrCardEncryption  = errors.New("dpay: card encryption failed")
	ErrInvalidArgument = errors.New("dpay: invalid argument")
)

Sentinel errors for classifying failures with errors.Is.

Functions

func Bool

func Bool(b bool) *bool

Bool returns a pointer to b, for optional bool fields. Use it to send false explicitly.

func EncryptCard

func EncryptCard(card CardData, transactionID, publicKeyPEM string) (string, error)

EncryptCard encrypts card data for a transaction with the public key fetched from Cards.PublicKey. dpay rotates that key, so fetch it before every attempt.

func Int

func Int(i int) *int

Int returns a pointer to i, for optional int fields.

func Int64

func Int64(i int64) *int64

Int64 returns a pointer to i, for optional int64 fields.

func String

func String(s string) *string

String returns a pointer to s, for optional string fields.

Types

type APIError

type APIError struct {

	// HTTPStatus is the response status. Rejections reported with HTTP 200 keep 200 here.
	HTTPStatus int
	// ErrorCode is the API error code, empty when the response carries none.
	ErrorCode string
	// FieldErrors maps a field name to its validation messages.
	FieldErrors map[string][]string
	// RawBody is the unparsed response body.
	RawBody string
	// contains filtered or unexported fields
}

APIError is returned whenever the dpay API reports a failure. Use errors.Is with one of the sentinels to classify it and errors.As to read its fields.

Example
package main

import (
	"context"
	"errors"
	"fmt"

	dpay "github.com/dpayglobal/dpay-go-sdk"
)

func main() {
	client, _ := dpay.New("my_shop", "secret_hash")
	_, err := client.Payments.Details(context.Background(), "tx-1")

	switch {
	case errors.Is(err, dpay.ErrNotFound):
		fmt.Println("no such transaction")
	case errors.Is(err, dpay.ErrTransport):
		fmt.Println("network failure, payment status unknown")
	case err != nil:
		var apiErr *dpay.APIError
		if errors.As(err, &apiErr) {
			fmt.Println(apiErr.HTTPStatus, apiErr.FieldErrors)
		}
	}
}

func (*APIError) Error

func (e *APIError) Error() string

Error implements error.

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is reports whether the error matches ErrAPI or its specific sentinel.

type ApplePayRequest

type ApplePayRequest struct {
	// DeviceInfo describes the payer browser.
	DeviceInfo DeviceInfo
	// Token is the Apple Pay payment token, ignored when Init is set.
	Token *string
	// ChannelID selects the acquiring channel.
	ChannelID *int
	// Init requests a session instead of a payment.
	Init bool
}

ApplePayRequest starts an Apple Pay session or pays with its token.

func (*ApplePayRequest) Validate

func (r *ApplePayRequest) Validate() error

Validate reports whether the device info is acceptable.

type Bank

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

Bank is a single bank offered on the payment page.

func (*Bank) ID

func (b *Bank) ID() string

ID returns the bank identifier used when preselecting a channel.

func (*Bank) Image

func (b *Bank) Image() string

Image returns the logo URL, empty when the API sent none.

func (*Bank) IsTest

func (b *Bank) IsTest() bool

IsTest reports whether this is a sandbox bank.

func (*Bank) Iterator

func (b *Bank) Iterator() *int64

Iterator returns the display order, nil when the API sent none.

func (*Bank) Name

func (b *Bank) Name() string

Name returns the display name.

func (*Bank) OnFrom

func (b *Bank) OnFrom() int64

OnFrom returns the hour from which the bank accepts payments.

func (*Bank) OnTo

func (b *Bank) OnTo() int64

OnTo returns the hour until which the bank accepts payments.

func (*Bank) Raw

func (b *Bank) Raw() map[string]any

Raw returns the decoded bank object.

func (*Bank) Type

func (b *Bank) Type() string

Type returns the bank type.

type BankService

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

BankService lists the banks available for online transfers.

func (*BankService) All

func (s *BankService) All(ctx context.Context) ([]*Bank, error)

All returns every bank dpay supports.

func (*BankService) ForService

func (s *BankService) ForService(ctx context.Context, opts ...TimestampOption) ([]*Bank, error)

ForService returns the banks enabled for this payment point. Without WithTimestamp the current time is sent, exactly as the PHP SDK does.

type BaseURLs

type BaseURLs struct {
	// APIPayments defaults to https://api-payments.dpay.pl.
	APIPayments string
	// Panel defaults to https://panel.dpay.pl.
	Panel string
	// Gateway defaults to https://secure.dpay.pl.
	Gateway string
}

BaseURLs overrides the API hosts. An empty field keeps the production default.

type BlikAlias

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

BlikAlias is a registered BLIK alias.

func (*BlikAlias) Apps

func (a *BlikAlias) Apps() []*BlikApp

Apps returns the banking apps the alias is registered in.

func (*BlikAlias) ExpirationDate

func (a *BlikAlias) ExpirationDate() string

ExpirationDate returns when the alias expires.

func (*BlikAlias) IsActive

func (a *BlikAlias) IsActive() bool

IsActive reports whether the alias status is ACTIVE.

func (*BlikAlias) Raw

func (a *BlikAlias) Raw() map[string]any

Raw returns the decoded data object.

func (*BlikAlias) Status

func (a *BlikAlias) Status() string

Status returns the alias status as reported by the API.

func (*BlikAlias) Type

func (a *BlikAlias) Type() BlikAliasType

Type returns the alias type.

func (*BlikAlias) Value

func (a *BlikAlias) Value() string

Value returns the alias value.

type BlikAliasRegistration

type BlikAliasRegistration struct {
	// Label is shown to the payer in their banking app, 1-50 characters.
	Label string
	// Type selects the alias kind.
	Type BlikAliasType
}

BlikAliasRegistration asks dpay to register a BLIK alias during a payment.

func (BlikAliasRegistration) Validate

func (b BlikAliasRegistration) Validate() error

Validate reports whether the label length and alias type are acceptable.

type BlikAliasType

type BlikAliasType string

BlikAliasType distinguishes a device alias from a PayID alias.

const (
	BlikAliasTypeUID   BlikAliasType = "UID"
	BlikAliasTypePayID BlikAliasType = "PAYID"
)

BLIK alias types.

func (BlikAliasType) Valid

func (t BlikAliasType) Valid() bool

Valid reports whether the value is one of the known alias types.

type BlikApp

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

BlikApp is a banking app an alias is registered in.

func (*BlikApp) Key

func (a *BlikApp) Key() string

Key returns the app identifier.

func (*BlikApp) Label

func (a *BlikApp) Label() string

Label returns the app display name.

type BlikRecurringInfo

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

BlikRecurringInfo carries the terms of a registered BLIK mandate.

func (*BlikRecurringInfo) Frequency

func (i *BlikRecurringInfo) Frequency() string

Frequency returns the charge interval.

func (*BlikRecurringInfo) InitDate

func (i *BlikRecurringInfo) InitDate() string

InitDate returns the first charge date.

func (*BlikRecurringInfo) IsLimitAmtFixed

func (i *BlikRecurringInfo) IsLimitAmtFixed() *bool

IsLimitAmtFixed reports whether the limit is fixed, nil when absent.

func (*BlikRecurringInfo) Label

func (i *BlikRecurringInfo) Label() string

Label returns the label shown to the payer.

func (*BlikRecurringInfo) LimitAmt

func (i *BlikRecurringInfo) LimitAmt() *int64

LimitAmt returns the per-charge limit in minor units, nil when absent.

func (*BlikRecurringInfo) Model

func (i *BlikRecurringInfo) Model() string

Model returns the mandate model.

func (*BlikRecurringInfo) Raw

func (i *BlikRecurringInfo) Raw() map[string]any

Raw returns the decoded registration object.

func (*BlikRecurringInfo) RegisteredAt

func (i *BlikRecurringInfo) RegisteredAt() string

RegisteredAt returns when the mandate was registered.

func (*BlikRecurringInfo) TotLimitAmt

func (i *BlikRecurringInfo) TotLimitAmt() *int64

TotLimitAmt returns the total limit in minor units, nil when absent.

type BlikRecurringModel

type BlikRecurringModel string

BlikRecurringModel is the mandate model of a BLIK recurring registration.

const (
	BlikRecurringModelAutomatic BlikRecurringModel = "A"
	BlikRecurringModelManual    BlikRecurringModel = "M"
	BlikRecurringModelOnDemand  BlikRecurringModel = "O"
)

BLIK recurring models: automatic, manual and on-demand.

func (BlikRecurringModel) Valid

func (m BlikRecurringModel) Valid() bool

Valid reports whether the value is one of the known recurring models.

type BlikRecurringRegistration

type BlikRecurringRegistration struct {
	// Label is shown to the payer, 1-50 characters.
	Label string
	// Model is the mandate model.
	Model BlikRecurringModel
	// Frequency matches ^[1-9][0-9]{0,2}[DWMQY]$, for example 1M.
	Frequency string
	// Value is the recurring amount, sent as a decimal string.
	Value *Money
	// LimitAmt is the per-charge limit in minor units.
	LimitAmt *int
	// TotLimitAmt is the total limit in minor units.
	TotLimitAmt *int
	// LimitAmtFixed marks the limit as fixed.
	LimitAmtFixed *bool
	// ExpirationDate is the mandate expiry in YYYY-MM-DD format.
	ExpirationDate *string
	// InitDate is the first charge date in YYYY-MM-DD format.
	InitDate *string
}

BlikRecurringRegistration asks dpay to register a BLIK recurring mandate.

func (BlikRecurringRegistration) Validate

func (b BlikRecurringRegistration) Validate() error

Validate reports whether the label, model, frequency and dates are acceptable.

type BlikRecurringStatus

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

BlikRecurringStatus is the state of a BLIK recurring mandate.

func (*BlikRecurringStatus) ExpirationDate

func (s *BlikRecurringStatus) ExpirationDate() string

ExpirationDate returns when the mandate expires.

func (*BlikRecurringStatus) IsActive

func (s *BlikRecurringStatus) IsActive() bool

IsActive reports whether the mandate status is ACTIVE.

func (*BlikRecurringStatus) Raw

func (s *BlikRecurringStatus) Raw() map[string]any

Raw returns the decoded data object.

func (*BlikRecurringStatus) Registration

func (s *BlikRecurringStatus) Registration() *BlikRecurringInfo

Registration returns the mandate terms, nil when the API sent none.

func (*BlikRecurringStatus) Status

func (s *BlikRecurringStatus) Status() string

Status returns the mandate status as reported by the API.

func (*BlikRecurringStatus) Type

Type returns the alias type.

func (*BlikRecurringStatus) Value

func (s *BlikRecurringStatus) Value() string

Value returns the alias value.

type BlikService

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

BlikService manages BLIK aliases and recurring mandates.

func (*BlikService) Alias

func (s *BlikService) Alias(ctx context.Context, aliasValue string, aliasType BlikAliasType) (*BlikAlias, error)

Alias registers a BLIK alias and returns its state.

func (*BlikService) RecurringStatus

func (s *BlikService) RecurringStatus(ctx context.Context, aliasValue string) (*BlikRecurringStatus, error)

RecurringStatus reads the state of a BLIK recurring mandate.

func (*BlikService) UnregisterAlias

func (s *BlikService) UnregisterAlias(ctx context.Context, aliasValue string, aliasType BlikAliasType, opts ...UnregisterOption) error

UnregisterAlias removes a BLIK alias.

type CardData

type CardData struct {
	// PAN is the card number, 12-19 digits. Spaces are stripped.
	PAN string
	// CVV is the security code, 3-4 digits.
	CVV string
	// Expiry is the expiry date in MM/YY format.
	Expiry string
}

CardData is the raw card the payer entered. It never leaves the process unencrypted: pass it to EncryptCard and send only the result.

func (CardData) Normalized

func (c CardData) Normalized() CardData

Normalized returns the card with spaces stripped from the PAN.

func (CardData) Validate

func (c CardData) Validate() error

Validate reports whether the card number, security code and expiry are well formed.

type CardEncryptionError

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

CardEncryptionError is returned when card data cannot be encrypted.

func (*CardEncryptionError) Error

func (e *CardEncryptionError) Error() string

Error implements error.

func (*CardEncryptionError) Is

func (e *CardEncryptionError) Is(target error) bool

Is reports whether the error matches ErrCardEncryption.

func (*CardEncryptionError) Unwrap

func (e *CardEncryptionError) Unwrap() error

Unwrap returns the underlying cause, if any.

type CardPaymentError

type CardPaymentError struct {
	*APIError
}

CardPaymentError is returned when a card operation fails with HTTP 200 and success != true.

func (*CardPaymentError) Unwrap

func (e *CardPaymentError) Unwrap() error

Unwrap exposes the embedded APIError to errors.As.

type CardPaymentRequest

type CardPaymentRequest struct {
	// DeviceInfo describes the payer browser and is always sent.
	DeviceInfo DeviceInfo
	// Email is the payer address.
	Email *string
	// ChannelID selects the acquiring channel.
	ChannelID *int
	// CardHolderFirstName is the name printed on the card.
	CardHolderFirstName *string
	// CardHolderLastName is the surname printed on the card.
	CardHolderLastName *string
	// EncryptedCardData is the result of EncryptCard.
	EncryptedCardData *string
	// ThreeDSConfirmed marks the 3-D Secure challenge as completed.
	ThreeDSConfirmed *bool
	// DCCDecision answers a dynamic currency conversion offer.
	DCCDecision DCCDecision
}

CardPaymentRequest carries a card payment or pre-authorization.

func (*CardPaymentRequest) Validate

func (r *CardPaymentRequest) Validate() error

Validate reports whether the device info and DCC decision are acceptable.

type CardPaymentResult

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

CardPaymentResult is the outcome of a card operation.

func (*CardPaymentResult) DCCOffer

func (r *CardPaymentResult) DCCOffer() *DCCOffer

DCCOffer returns the currency conversion offer, nil when there is none.

func (*CardPaymentResult) HasDCCOffer

func (r *CardPaymentResult) HasDCCOffer() bool

HasDCCOffer reports whether the payer must answer a currency conversion offer.

func (*CardPaymentResult) IsSuccess

func (r *CardPaymentResult) IsSuccess() bool

IsSuccess reports whether the payment finished without further steps.

func (*CardPaymentResult) Raw

func (r *CardPaymentResult) Raw() map[string]any

Raw returns the decoded response body.

func (*CardPaymentResult) RedirectType

func (r *CardPaymentResult) RedirectType() RedirectType

RedirectType returns what the merchant should do next.

func (*CardPaymentResult) RedirectURL

func (r *CardPaymentResult) RedirectURL() string

RedirectURL returns the decoded redirect target, empty when there is none.

func (*CardPaymentResult) RequiresRedirect

func (r *CardPaymentResult) RequiresRedirect() bool

RequiresRedirect reports whether the payer must be redirected.

func (*CardPaymentResult) RequiresThreeDSForm

func (r *CardPaymentResult) RequiresThreeDSForm() bool

RequiresThreeDSForm reports whether a 3-D Secure form must be rendered.

func (*CardPaymentResult) ThreeDSFormHTML

func (r *CardPaymentResult) ThreeDSFormHTML() string

ThreeDSFormHTML returns the decoded 3-D Secure form, empty when there is none.

type CardRecurringFrequency

type CardRecurringFrequency string

CardRecurringFrequency is the charge interval of a card mandate.

const (
	CardRecurringFrequencyDaily      CardRecurringFrequency = "DAILY"
	CardRecurringFrequencyWeekly     CardRecurringFrequency = "WEEKLY"
	CardRecurringFrequencyBiweekly   CardRecurringFrequency = "BIWEEKLY"
	CardRecurringFrequencyMonthly    CardRecurringFrequency = "MONTHLY"
	CardRecurringFrequencyQuarterly  CardRecurringFrequency = "QUARTERLY"
	CardRecurringFrequencySemiannual CardRecurringFrequency = "SEMIANNUAL"
	CardRecurringFrequencyAnnual     CardRecurringFrequency = "ANNUAL"
)

Card recurring frequencies.

func (CardRecurringFrequency) Valid

func (f CardRecurringFrequency) Valid() bool

Valid reports whether the value is one of the known frequencies.

type CardRecurringOperation

type CardRecurringOperation string

CardRecurringOperation selects what a card-on-file registration does.

const (
	CardRecurringOperationAddCard    CardRecurringOperation = "add_card"
	CardRecurringOperationCOFInitial CardRecurringOperation = "cof_initial"
	CardRecurringOperationCharge     CardRecurringOperation = "charge"
)

Card recurring operations.

func (CardRecurringOperation) Valid

func (o CardRecurringOperation) Valid() bool

Valid reports whether the value is one of the known operations.

type CardRecurringRegistration

type CardRecurringRegistration struct {
	// Label is shown to the payer, 1-50 characters.
	Label string
	// Frequency is the charge interval, empty when not declared.
	Frequency CardRecurringFrequency
	// LimitAmt is the per-charge limit, sent in minor units.
	LimitAmt *Money
	// TotLimitAmt is the total limit, sent in minor units.
	TotLimitAmt *Money
	// LimitAmtFixed marks the limit as fixed.
	LimitAmtFixed *bool
	// ExpirationDate is the mandate expiry in YYYY-MM-DD format.
	ExpirationDate *string
	// InitDate is the first charge date in YYYY-MM-DD format.
	InitDate *string
}

CardRecurringRegistration asks dpay to register a card-on-file mandate.

func (CardRecurringRegistration) Validate

func (c CardRecurringRegistration) Validate() error

Validate reports whether the label, frequency and dates are acceptable.

type CardService

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

CardService runs server-to-server card operations.

func (*CardService) ApplePay

func (s *CardService) ApplePay(ctx context.Context, transactionID string, request *ApplePayRequest) (*CardPaymentResult, error)

ApplePay starts an Apple Pay session or charges its token.

func (*CardService) Cancel

func (s *CardService) Cancel(ctx context.Context, transactionID string, amount *Money) (*CardPaymentResult, error)

Cancel voids a pre-authorization. A nil amount cancels the full amount.

func (*CardService) Capture

func (s *CardService) Capture(ctx context.Context, transactionID string, amount *Money) (*CardPaymentResult, error)

Capture settles a pre-authorization. A nil amount captures the full amount.

func (*CardService) GooglePay

func (s *CardService) GooglePay(ctx context.Context, transactionID string, request *GooglePayRequest) (*CardPaymentResult, error)

GooglePay charges a Google Pay token.

func (*CardService) PayOTP

func (s *CardService) PayOTP(ctx context.Context, transactionID string, request *CardPaymentRequest) (*CardPaymentResult, error)

PayOTP charges an encrypted card.

func (*CardService) PreAuth

func (s *CardService) PreAuth(ctx context.Context, transactionID string, request *CardPaymentRequest) (*CardPaymentResult, error)

PreAuth authorizes an encrypted card without capturing.

func (*CardService) PublicKey

func (s *CardService) PublicKey(ctx context.Context) (string, error)

PublicKey fetches the RSA key used to encrypt card data. dpay rotates it, so fetch it before every payment attempt rather than caching it.

type Client

type Client struct {
	// Payments registers payments and reads transaction details.
	Payments *PaymentService
	// Refunds creates refunds and checks their availability.
	Refunds *RefundService
	// Banks lists the available banks.
	Banks *BankService
	// Blik manages BLIK aliases and recurring registrations.
	Blik *BlikService
	// Cards runs server-to-server card operations.
	Cards *CardService
	// Payouts reads payout details.
	Payouts *PayoutService
	// contains filtered or unexported fields
}

Client is the entry point to the dpay API. Its service fields are safe for concurrent use.

Example
package main

import (
	"context"
	"fmt"

	dpay "github.com/dpayglobal/dpay-go-sdk"
)

func main() {
	client, err := dpay.New("my_shop", "secret_hash")
	if err != nil {
		panic(err)
	}

	payment, err := client.Payments.Register(context.Background(), &dpay.RegisterPaymentRequest{
		Amount:          dpay.PLN(1050),
		TransactionType: dpay.TransactionTypeTransfers,
		URLs: dpay.ReturnURLs{
			Success: "https://twojsklep.pl/sukces",
			Fail:    "https://twojsklep.pl/blad",
			IPN:     "https://twojsklep.pl/ipn",
		},
		Description: dpay.String("Zamówienie #1234"),
		Custom:      dpay.String("order-1234"),
	})
	if err != nil {
		panic(err)
	}

	if url := payment.RedirectURL(); url != "" {
		fmt.Println("redirect to", url)
	}
}

func New

func New(service, secretHash string, opts ...Option) (*Client, error)

New returns a Client for a payment point identified by service and its secret hash.

func (*Client) Service

func (c *Client) Service() string

Service returns the payment point name the client authenticates as.

type Currency

type Currency string

Currency is an ISO 4217 alphabetic currency code.

const (
	CurrencyPLN Currency = "PLN"
	CurrencyEUR Currency = "EUR"
	CurrencyCZK Currency = "CZK"
)

Currencies used by the dpay API.

func (Currency) Valid

func (c Currency) Valid() bool

Valid reports whether the code consists of exactly three uppercase letters.

type DCCDecision

type DCCDecision string

DCCDecision is the cardholder's answer to a dynamic currency conversion offer.

const (
	DCCDecisionAccept DCCDecision = "accept"
	DCCDecisionReject DCCDecision = "reject"
)

DCC decisions.

func (DCCDecision) Valid

func (d DCCDecision) Valid() bool

Valid reports whether the value is one of the known DCC decisions.

type DCCMarkup

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

DCCMarkup is a single margin component of a conversion rate.

func (*DCCMarkup) AdditionalInfo

func (m *DCCMarkup) AdditionalInfo() string

AdditionalInfo returns the explanation of this margin component.

func (*DCCMarkup) Rate

func (m *DCCMarkup) Rate() float64

Rate returns the margin rate.

type DCCOffer

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

DCCOffer is a dynamic currency conversion offer the payer must accept or reject.

func (*DCCOffer) ConvertedAmount

func (o *DCCOffer) ConvertedAmount() Money

ConvertedAmount returns the amount in the cardholder currency.

func (*DCCOffer) CurrencyConversionID

func (o *DCCOffer) CurrencyConversionID() string

CurrencyConversionID identifies the offer.

func (*DCCOffer) DeclarationText

func (o *DCCOffer) DeclarationText() string

DeclarationText returns the PSD2 disclosure that must be shown to the payer.

func (*DCCOffer) ExchangeRate

func (o *DCCOffer) ExchangeRate() float64

ExchangeRate returns the offered rate.

func (*DCCOffer) IsEuropeanEconomicArea

func (o *DCCOffer) IsEuropeanEconomicArea() bool

IsEuropeanEconomicArea reports whether the card was issued in the EEA.

func (*DCCOffer) Markup

func (o *DCCOffer) Markup() []*DCCMarkup

Markup returns the margin components of the rate.

func (*DCCOffer) OriginalAmount

func (o *DCCOffer) OriginalAmount() Money

OriginalAmount returns the amount in the transaction currency.

func (*DCCOffer) Raw

func (o *DCCOffer) Raw() map[string]any

Raw returns the decoded offer object.

func (*DCCOffer) ValidUntil

func (o *DCCOffer) ValidUntil() string

ValidUntil returns when the offer expires.

type DeviceInfo

type DeviceInfo struct {
	// BrowserAcceptHeader is the Accept header of the payer's browser.
	BrowserAcceptHeader string
	// BrowserLanguage is the browser language tag.
	BrowserLanguage string
	// BrowserColorDepth is the screen color depth in bits.
	BrowserColorDepth int
	// BrowserScreenHeight is the screen height in pixels.
	BrowserScreenHeight int
	// BrowserScreenWidth is the screen width in pixels.
	BrowserScreenWidth int
	// BrowserTZ is the timezone offset in minutes.
	BrowserTZ int
	// BrowserUserAgent is the browser User-Agent string.
	BrowserUserAgent string
	// SystemFamily is the operating system family.
	SystemFamily string
	// GeoLocalization is the payer's coordinates.
	GeoLocalization string
	// DeviceID identifies the device, 1-64 characters. Sent as deviceID.
	DeviceID string
	// ApplicationName identifies the merchant application, 1-64 characters.
	ApplicationName string
	// BrowserJavaEnabled is sent as the string "true" or "false" when set.
	BrowserJavaEnabled *bool
}

DeviceInfo describes the payer's browser, required by 3-D Secure.

func (DeviceInfo) Validate

func (d DeviceInfo) Validate() error

Validate reports whether DeviceID and ApplicationName are within range.

type Fields

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

Fields is an ordered map for request fields the API accepts as free-form objects: billing address, shipping address and product entries. Order matters because the SDK serializes fields in insertion order.

func NewFields

func NewFields() *Fields

NewFields returns an empty Fields.

func (*Fields) MarshalJSON

func (f *Fields) MarshalJSON() ([]byte, error)

MarshalJSON serializes the fields in insertion order.

func (*Fields) Set

func (f *Fields) Set(key string, value any) *Fields

Set stores value under key and returns the receiver so calls can be chained.

type GooglePayRequest

type GooglePayRequest struct {
	// Token is the Google Pay payment token.
	Token string
	// DeviceInfo describes the payer browser.
	DeviceInfo DeviceInfo
	// Email is the payer address.
	Email *string
	// ChannelID selects the acquiring channel.
	ChannelID *int
}

GooglePayRequest carries a Google Pay token.

func (*GooglePayRequest) Validate

func (r *GooglePayRequest) Validate() error

Validate reports whether the device info is acceptable.

type HTTPDoer

type HTTPDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPDoer is the transport the client sends requests through. *http.Client satisfies it, which is the point: retries, proxies and instrumentation are configured with a custom http.Client or RoundTripper.

type IPNEvent

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

IPNEvent is a verified IPN notification.

func VerifyIPN

func VerifyIPN(rawBody []byte, secretHash string) (*IPNEvent, error)

VerifyIPN parses and authenticates an IPN notification. Always compare the amount with your own order before marking it as paid.

Example
package main

import (
	"fmt"
	"net/http"

	dpay "github.com/dpayglobal/dpay-go-sdk"
)

func main() {
	handler := func(w http.ResponseWriter, r *http.Request) {
		body := make([]byte, r.ContentLength)
		r.Body.Read(body)

		event, err := dpay.VerifyIPN(body, "secret_hash")
		if err != nil {
			http.Error(w, "invalid signature", http.StatusBadRequest)
			return
		}
		if event.IsTransfer() || event.IsCapture() {
			markOrderAsPaid(event.ID(), event.Amount())
		}
		fmt.Fprint(w, dpay.IPNAck)
	}
	_ = handler
}

func markOrderAsPaid(id, amount string) {}

func (*IPNEvent) Amount

func (e *IPNEvent) Amount() string

Amount returns the amount as the raw decimal string from the payload. The payload carries no currency, so compare this with your own order.

func (*IPNEvent) Attempt

func (e *IPNEvent) Attempt() int64

Attempt returns which delivery attempt this is.

func (*IPNEvent) CapturePaymentID

func (e *IPNEvent) CapturePaymentID() string

CapturePaymentID returns the capture identifier, empty for other event types.

func (*IPNEvent) Custom

func (e *IPNEvent) Custom() string

Custom returns the merchant reference passed at registration.

func (*IPNEvent) Email

func (e *IPNEvent) Email() string

Email returns the payer address, empty when absent.

func (*IPNEvent) ID

func (e *IPNEvent) ID() string

ID returns the transaction identifier.

func (*IPNEvent) IsCapture

func (e *IPNEvent) IsCapture() bool

IsCapture reports whether this is a capture notification.

func (*IPNEvent) IsDCB

func (e *IPNEvent) IsDCB() bool

IsDCB reports whether this is a direct carrier billing notification.

func (*IPNEvent) IsTransfer

func (e *IPNEvent) IsTransfer() bool

IsTransfer reports whether this is a transfer notification.

func (*IPNEvent) Raw

func (e *IPNEvent) Raw() map[string]any

Raw returns the decoded payload.

func (*IPNEvent) Signature

func (e *IPNEvent) Signature() string

Signature returns the signature the notification carried.

func (*IPNEvent) Type

func (e *IPNEvent) Type() IPNType

Type returns the event type.

func (*IPNEvent) Version

func (e *IPNEvent) Version() int64

Version returns the notification format version.

type IPNType

type IPNType string

IPNType is the kind of event an IPN notification reports.

const (
	IPNTypeTransfer IPNType = "transfer"
	IPNTypeCapture  IPNType = "capture"
	IPNTypeDCB      IPNType = "dcb"
)

IPN types.

func (IPNType) Valid

func (t IPNType) Valid() bool

Valid reports whether the value is one of the known IPN types.

type InvoiceDetails

type InvoiceDetails struct {
	// PayerNIP is the payer's tax identification number.
	PayerNIP *string
	// PayerName is the payer's legal name.
	PayerName *string
	// InvoiceNumber is the merchant's invoice number.
	InvoiceNumber *string
	// PaymentDueDate is the due date in YYYY-MM-DD format.
	PaymentDueDate *string
	// VatAmount is the VAT amount, sent in minor units.
	VatAmount *Money
}

InvoiceDetails carries the KSeF e-invoice data attached to a registration.

func (InvoiceDetails) Validate

func (i InvoiceDetails) Validate() error

Validate reports whether the due date, when present, is well formed.

type Money

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

Money is an amount in minor units together with its currency.

func NewMoney

func NewMoney(minor int64, currency Currency) (Money, error)

NewMoney returns an amount in minor units of the given currency.

func PLN

func PLN(minor int64) Money

PLN returns an amount in Polish grosz.

func ParseMoney

func ParseMoney(decimal string, currency Currency) (Money, error)

ParseMoney parses a decimal string with at most two fraction digits.

func (Money) Currency

func (m Money) Currency() Currency

Currency returns the currency code.

func (Money) Equal

func (m Money) Equal(other Money) bool

Equal reports whether both the amount and the currency match.

func (Money) IsNegative

func (m Money) IsNegative() bool

IsNegative reports whether the amount is below zero.

func (Money) IsZero

func (m Money) IsZero() bool

IsZero reports whether the amount is zero.

func (Money) Minor

func (m Money) Minor() int64

Minor returns the amount in minor units.

func (Money) String

func (m Money) String() string

String returns the amount as a decimal with exactly two fraction digits.

type Option

type Option func(*clientConfig)

Option configures a Client.

func WithBaseURLs

func WithBaseURLs(urls BaseURLs) Option

WithBaseURLs overrides the API hosts, trimming trailing slashes.

func WithHTTPClient

func WithHTTPClient(doer HTTPDoer) Option

WithHTTPClient sets the transport used for every request.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the timeout of the default HTTP client. It is ignored when WithHTTPClient is used.

type Payer

type Payer struct {
	// Email is the payer address, validated when present.
	Email *string
	// FirstName is sent as client_name.
	FirstName *string
	// LastName is sent as client_surname.
	LastName *string
}

Payer carries the optional payer identity sent with a registration.

func (Payer) Validate

func (p Payer) Validate() error

Validate reports whether the email, when present, is well formed.

type PaymentRejectedError

type PaymentRejectedError struct {
	*APIError

	// TransactionID is the identifier the API assigned before rejecting, may be empty.
	TransactionID string
}

PaymentRejectedError is returned when payment registration is rejected with HTTP 200.

func (*PaymentRejectedError) Unwrap

func (e *PaymentRejectedError) Unwrap() error

Unwrap exposes the embedded APIError to errors.As.

type PaymentService

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

PaymentService registers payments and reads transaction details.

func (*PaymentService) Details

func (s *PaymentService) Details(ctx context.Context, transactionID string) (*Transaction, error)

Details reads the current state of a transaction.

func (*PaymentService) Register

Register creates a payment and returns the redirect target or the inline result.

type PayoutDetails

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

PayoutDetails is the state of a single payout.

func (*PayoutDetails) CreationDate

func (p *PayoutDetails) CreationDate() string

CreationDate returns the creation timestamp as reported by the API.

func (*PayoutDetails) DeclineReason

func (p *PayoutDetails) DeclineReason() string

DeclineReason returns why the payout was declined.

func (*PayoutDetails) DeclineStatus

func (p *PayoutDetails) DeclineStatus() string

DeclineStatus returns the decline status code.

func (*PayoutDetails) Fee

func (p *PayoutDetails) Fee() Money

Fee returns the fee charged.

func (*PayoutDetails) Gross

func (p *PayoutDetails) Gross() Money

Gross returns the amount including fees.

func (*PayoutDetails) ID

func (p *PayoutDetails) ID() int64

ID returns the payout identifier.

func (*PayoutDetails) IsDeclined

func (p *PayoutDetails) IsDeclined() bool

IsDeclined reports whether the payout was declined.

func (*PayoutDetails) IsDirectSettlement

func (p *PayoutDetails) IsDirectSettlement() bool

IsDirectSettlement reports whether this was a direct settlement.

func (*PayoutDetails) IsFailed

func (p *PayoutDetails) IsFailed() bool

IsFailed reports whether the payout failed.

func (*PayoutDetails) IsProcessed

func (p *PayoutDetails) IsProcessed() bool

IsProcessed reports whether the payout was sent.

func (*PayoutDetails) IsWaiting

func (p *PayoutDetails) IsWaiting() bool

IsWaiting reports whether the payout is still queued.

func (*PayoutDetails) NRB

func (p *PayoutDetails) NRB() string

NRB returns the account number the payout was sent to.

func (*PayoutDetails) Net

func (p *PayoutDetails) Net() Money

Net returns the amount before fees.

func (*PayoutDetails) Raw

func (p *PayoutDetails) Raw() map[string]any

Raw returns the decoded response body.

func (*PayoutDetails) Receiver

func (p *PayoutDetails) Receiver() *PayoutReceiver

Receiver returns the payout recipient, nil when the API sent none.

func (*PayoutDetails) State

func (p *PayoutDetails) State() int64

State returns the raw state code: 0 waiting, 1 processed, -1 failed.

type PayoutFeeMode

type PayoutFeeMode string

PayoutFeeMode decides whether payout positions are net or gross of fees.

const (
	PayoutFeeModeNet   PayoutFeeMode = "net"
	PayoutFeeModeGross PayoutFeeMode = "gross"
)

Payout fee modes.

func (PayoutFeeMode) Valid

func (m PayoutFeeMode) Valid() bool

Valid reports whether the value is one of the known fee modes.

type PayoutInstruction

type PayoutInstruction struct {
	// Positions must hold at least one entry.
	Positions []PayoutPosition
	// FeeMode decides whether positions are net or gross of fees.
	FeeMode PayoutFeeMode
}

PayoutInstruction splits a payment into 1:1 payouts.

func (PayoutInstruction) Validate

func (p PayoutInstruction) Validate() error

Validate reports whether the instruction has positions, a known fee mode and valid lines.

type PayoutPosition

type PayoutPosition struct {
	// IBAN is the receiving account.
	IBAN string
	// Title is the transfer title, 1-255 characters.
	Title string
	// Amount is the payout amount, sent as a float.
	Amount Money
}

PayoutPosition is a single 1:1 payout instruction line.

func (PayoutPosition) Validate

func (p PayoutPosition) Validate() error

Validate reports whether the IBAN and title are within range.

type PayoutReceiver

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

PayoutReceiver is the recipient of a payout.

func (*PayoutReceiver) Amount

func (r *PayoutReceiver) Amount() (Money, bool)

Amount returns the payout amount and whether the API sent a parsable one.

func (*PayoutReceiver) NRB

func (r *PayoutReceiver) NRB() string

NRB returns the recipient account number.

func (*PayoutReceiver) Raw

func (r *PayoutReceiver) Raw() map[string]any

Raw returns the decoded receiver object.

func (*PayoutReceiver) ReceiverAddress

func (r *PayoutReceiver) ReceiverAddress() string

ReceiverAddress returns the recipient address.

func (*PayoutReceiver) ReceiverName

func (r *PayoutReceiver) ReceiverName() string

ReceiverName returns the recipient name.

func (*PayoutReceiver) Service

func (r *PayoutReceiver) Service() string

Service returns the payment point the payout came from.

func (*PayoutReceiver) Title

func (r *PayoutReceiver) Title() string

Title returns the transfer title.

type PayoutService

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

PayoutService reads the state of payouts.

func (*PayoutService) Details

func (s *PayoutService) Details(ctx context.Context, withdrawID int64, opts ...TimestampOption) (*PayoutDetails, error)

Details reads a payout by its withdraw identifier. Without WithTimestamp no timestamp field is sent at all, matching the PHP SDK.

type RateLimitError

type RateLimitError struct {
	*APIError

	// RetryAfter is the Retry-After header in seconds, nil when absent.
	RetryAfter *int
	// Limit is the X-RateLimit-Limit header, nil when absent.
	Limit *int
	// Remaining is the X-RateLimit-Remaining header, nil when absent.
	Remaining *int
}

RateLimitError is returned for HTTP 429 and carries the rate limit headers.

func (*RateLimitError) Unwrap

func (e *RateLimitError) Unwrap() error

Unwrap exposes the embedded APIError to errors.As.

type RedirectType

type RedirectType string

RedirectType tells the merchant what to do with a card payment result.

const (
	RedirectTypeSuccess  RedirectType = "SUCCESS"
	RedirectTypeForm     RedirectType = "FORM"
	RedirectTypeURL      RedirectType = "URL"
	RedirectTypeDCCOffer RedirectType = "DCC_OFFER"
)

Redirect types returned by card operations.

func (RedirectType) Valid

func (t RedirectType) Valid() bool

Valid reports whether the value is one of the known redirect types.

type Refund

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

Refund is the outcome of a refund request.

func (*Refund) IsAccepted

func (r *Refund) IsAccepted() bool

IsAccepted reports whether dpay accepted the refund.

func (*Refund) Message

func (r *Refund) Message() string

Message returns the message the API returned.

func (*Refund) Raw

func (r *Refund) Raw() map[string]any

Raw returns the decoded response body.

type RefundAvailability

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

RefundAvailability reports whether a transaction can still be refunded.

func (*RefundAvailability) HTTPStatus

func (a *RefundAvailability) HTTPStatus() int

HTTPStatus returns the status the API answered with, which encodes the reason.

func (*RefundAvailability) IsAvailable

func (a *RefundAvailability) IsAvailable() bool

IsAvailable reports whether a refund can be issued.

func (*RefundAvailability) Message

func (a *RefundAvailability) Message() string

Message returns the explanation the API returned.

func (*RefundAvailability) Raw

func (a *RefundAvailability) Raw() map[string]any

Raw returns the decoded response body.

type RefundOption

type RefundOption func(*refundOptions)

RefundOption sets an optional field of a refund request. Unlike an absent option, an explicitly set value is always sent and always enters the checksum.

func WithRefundAmount

func WithRefundAmount(amount Money) RefundOption

WithRefundAmount refunds only part of the transaction.

func WithRefundReason

func WithRefundReason(reason string) RefundOption

WithRefundReason attaches a reason to the refund.

type RefundService

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

RefundService creates refunds and checks their availability.

func (*RefundService) CheckAvailability

func (s *RefundService) CheckAvailability(ctx context.Context, transactionID string, opts ...RefundOption) (*RefundAvailability, error)

CheckAvailability reports whether a refund can be issued. Statuses the API uses to express a business outcome are returned as a result, not as an error.

func (*RefundService) Create

func (s *RefundService) Create(ctx context.Context, transactionID string, opts ...RefundOption) (*Refund, error)

Create refunds a transaction, in full unless WithRefundAmount narrows it.

type RegisterPaymentRequest

type RegisterPaymentRequest struct {
	// Amount is the transaction amount.
	Amount Money
	// TransactionType selects the payment flow.
	TransactionType TransactionType
	// URLs are the success, failure and IPN endpoints.
	URLs ReturnURLs

	// Description is shown to the payer.
	Description *string
	// Custom is an opaque merchant reference echoed back in the IPN.
	Custom *string
	// Payer carries the payer identity.
	Payer *Payer
	// AcceptTos marks the terms of service as accepted.
	AcceptTos *bool
	// Channel preselects a payment channel.
	Channel *string

	// CreditCard toggles the card channel, sent as 0 or 1.
	CreditCard *bool
	// Paysafecard toggles the paysafecard channel, sent as 0 or 1.
	Paysafecard *bool
	// Blik toggles the BLIK channel, sent as 0 or 1.
	Blik *bool
	// Installment toggles installments, sent as 0 or 1.
	Installment *bool
	// PayPal toggles PayPal, sent as 0 or 1.
	PayPal *bool
	// NoBanks hides bank transfers, sent as 0 or 1.
	NoBanks *bool

	// PhoneNumber is the payer phone number for direct carrier billing.
	PhoneNumber *string
	// CurrencyCode overrides the transaction currency.
	CurrencyCode Currency
	// PartnerPlatform identifies the integration platform, matching ^[A-Z0-9]{1,64}$.
	PartnerPlatform *string
	// UserAgent is the payer browser User-Agent, required with BlikCode and BlikAlias.
	UserAgent *string
	// UserIP is the payer IP address, required with BlikCode and BlikAlias.
	UserIP *string

	// BlikCode is a six-digit BLIK code, mutually exclusive with BlikAlias.
	BlikCode *string
	// BlikAlias pays with a registered alias, mutually exclusive with BlikCode and alias registration.
	BlikAlias *string
	// RegisterBlikAlias registers a BLIK alias during this payment.
	RegisterBlikAlias *BlikAliasRegistration
	// RegisterBlikRecurringAlias registers a BLIK recurring mandate during this payment.
	RegisterBlikRecurringAlias *BlikRecurringRegistration
	// AliasIPNURL receives alias lifecycle notifications.
	AliasIPNURL *string
	// NoDelay requests immediate processing.
	NoDelay *bool

	// CardRecurring registers a card-on-file mandate, mutually exclusive with CardRecurringAlias.
	CardRecurring *CardRecurringRegistration
	// CardRecurringAlias charges a stored card, mutually exclusive with CardRecurring.
	CardRecurringAlias *string
	// AuthorizeOnly authorizes without capturing.
	AuthorizeOnly *bool
	// CardRecurringOperation selects the card-on-file operation.
	CardRecurringOperation CardRecurringOperation

	// Payout splits the payment into 1:1 payouts.
	Payout *PayoutInstruction
	// BillingAddress is a free-form object; use NewFields to control key order.
	BillingAddress any
	// ShippingAddress is a free-form object; use NewFields to control key order.
	ShippingAddress any
	// DeviceInfo describes the payer browser, required by 3-D Secure.
	DeviceInfo *DeviceInfo
	// Products lists the ordered items; use NewFields for each entry to control key order.
	Products []any
	// Efaktura requests a KSeF e-invoice; allowed only with TransactionTypeTransfers.
	Efaktura *bool
	// Invoice carries the e-invoice details.
	Invoice *InvoiceDetails
}

RegisterPaymentRequest describes a payment to register. Amount, TransactionType and URLs are required; every pointer field is omitted from the request when nil.

func (*RegisterPaymentRequest) Validate

func (r *RegisterPaymentRequest) Validate() error

Validate reports the first problem with the request, using the same messages as the PHP SDK. It is called automatically before the request is sent.

type RegisteredPayment

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

RegisteredPayment is the result of registering a payment.

func (*RegisteredPayment) CardRecurringAlias

func (p *RegisteredPayment) CardRecurringAlias() string

CardRecurringAlias returns the stored-card alias registered with this payment, if any.

func (*RegisteredPayment) IPKSeF

func (p *RegisteredPayment) IPKSeF() string

IPKSeF returns the KSeF invoice identifier, empty when the response carries none.

func (*RegisteredPayment) IsInlineProcessing

func (p *RegisteredPayment) IsInlineProcessing() bool

IsInlineProcessing reports whether the payment is being processed without a redirect.

func (*RegisteredPayment) IsPaid

func (p *RegisteredPayment) IsPaid() bool

IsPaid reports whether the payment completed during registration.

func (*RegisteredPayment) Message

func (p *RegisteredPayment) Message() string

Message returns the raw msg field, which carries either a redirect URL or a status phrase.

func (*RegisteredPayment) Raw

func (p *RegisteredPayment) Raw() map[string]any

Raw returns the decoded response body.

func (*RegisteredPayment) RedirectURL

func (p *RegisteredPayment) RedirectURL() string

RedirectURL returns the URL to send the payer to, or an empty string when the message is not a URL.

func (*RegisteredPayment) TransactionID

func (p *RegisteredPayment) TransactionID() string

TransactionID returns the identifier assigned to the payment.

type ReturnURLs

type ReturnURLs struct {
	// Success is where the payer lands after a successful payment.
	Success string
	// Fail is where the payer lands after a failed payment.
	Fail string
	// IPN receives the server-to-server payment notification.
	IPN string
}

ReturnURLs carries the three URLs dpay redirects to and notifies.

func (ReturnURLs) Validate

func (u ReturnURLs) Validate() error

Validate reports whether all three URLs are well formed.

type SignatureError

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

SignatureError is returned when an IPN payload is malformed or its signature does not match.

func (*SignatureError) Error

func (e *SignatureError) Error() string

Error implements error.

func (*SignatureError) Is

func (e *SignatureError) Is(target error) bool

Is reports whether the error matches ErrSignature.

type TimestampOption

type TimestampOption func(*int64)

TimestampOption overrides the timestamp an operation would otherwise read from the clock.

func WithTimestamp

func WithTimestamp(timestamp int64) TimestampOption

WithTimestamp pins the timestamp sent with the request.

type Transaction

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

Transaction is the state of a registered payment.

func (*Transaction) AvailableRefundAmount

func (t *Transaction) AvailableRefundAmount() Money

AvailableRefundAmount returns how much can still be refunded.

func (*Transaction) CreationDate

func (t *Transaction) CreationDate() string

CreationDate returns the creation timestamp as reported by the API.

func (*Transaction) GatewayID

func (t *Transaction) GatewayID() string

GatewayID returns the gateway identifier.

func (*Transaction) ID

func (t *Transaction) ID() string

ID returns the transaction identifier.

func (*Transaction) IsDirect

func (t *Transaction) IsDirect() bool

IsDirect reports whether the payment was a direct transaction.

func (*Transaction) IsFullyRefunded

func (t *Transaction) IsFullyRefunded() bool

IsFullyRefunded reports whether the whole amount was refunded.

func (*Transaction) IsPaid

func (t *Transaction) IsPaid() bool

IsPaid reports whether the transaction is paid or captured.

func (*Transaction) IsRefunded

func (t *Transaction) IsRefunded() bool

IsRefunded reports whether any refund was issued.

func (*Transaction) IsSettled

func (t *Transaction) IsSettled() bool

IsSettled reports whether the funds were settled to the merchant.

func (*Transaction) Payer

func (t *Transaction) Payer() map[string]any

Payer returns the payer object exactly as the API sent it.

func (*Transaction) PaymentDate

func (t *Transaction) PaymentDate() string

PaymentDate returns the payment timestamp as reported by the API.

func (*Transaction) PaymentMethod

func (t *Transaction) PaymentMethod() string

PaymentMethod returns the method the payer used.

func (*Transaction) Raw

func (t *Transaction) Raw() map[string]any

Raw returns the decoded response body.

func (*Transaction) RefundedAmount

func (t *Transaction) RefundedAmount() Money

RefundedAmount returns the total amount already refunded.

func (*Transaction) Refunds

func (t *Transaction) Refunds() []*TransactionRefund

Refunds returns the refunds issued against this transaction.

func (*Transaction) Status

func (t *Transaction) Status() TransactionStatus

Status returns the transaction status, preserved verbatim even when unknown.

func (*Transaction) Value

func (t *Transaction) Value() Money

Value returns the transaction amount.

type TransactionRefund

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

TransactionRefund is a single refund listed in transaction details.

func (*TransactionRefund) CreationDate

func (r *TransactionRefund) CreationDate() string

CreationDate returns the creation timestamp as reported by the API.

func (*TransactionRefund) PaymentDate

func (r *TransactionRefund) PaymentDate() string

PaymentDate returns the payment timestamp as reported by the API.

func (*TransactionRefund) PaymentID

func (r *TransactionRefund) PaymentID() string

PaymentID returns the refund payment identifier.

func (*TransactionRefund) Raw

func (r *TransactionRefund) Raw() map[string]any

Raw returns the decoded refund object.

func (*TransactionRefund) Status

Status returns the refund status.

func (*TransactionRefund) Value

func (r *TransactionRefund) Value() Money

Value returns the refunded amount.

type TransactionStatus

type TransactionStatus string

TransactionStatus is the lifecycle state of a transaction.

const (
	TransactionStatusPaid       TransactionStatus = "paid"
	TransactionStatusCreated    TransactionStatus = "created"
	TransactionStatusProcessing TransactionStatus = "processing"
	TransactionStatusExpired    TransactionStatus = "expired"
	TransactionStatusCaptured   TransactionStatus = "captured"
)

Transaction statuses reported by pbl/details.

func (TransactionStatus) Valid

func (s TransactionStatus) Valid() bool

Valid reports whether the value is one of the known transaction statuses.

type TransactionType

type TransactionType string

TransactionType selects the payment flow a registration starts.

const (
	TransactionTypeTransfers     TransactionType = "transfers"
	TransactionTypeDCBGateway    TransactionType = "dcb_gateway"
	TransactionTypeCardAuth      TransactionType = "card_auth"
	TransactionTypeMBWayDirect   TransactionType = "mb_way_direct"
	TransactionTypeBizumDirect   TransactionType = "bizum_direct"
	TransactionTypeBlikRecurring TransactionType = "blik_recurring"
	TransactionTypeCardRecurring TransactionType = "card_recurring"
)

Transaction types accepted by payments/register.

func (TransactionType) Valid

func (t TransactionType) Valid() bool

Valid reports whether the value is one of the known transaction types.

type TransportError

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

TransportError is returned when the request never produced an API response: network, DNS, TLS or context failures. The payment status is unknown.

func (*TransportError) Error

func (e *TransportError) Error() string

Error implements error.

func (*TransportError) Is

func (e *TransportError) Is(target error) bool

Is reports whether the error matches ErrTransport.

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

Unwrap returns the underlying cause.

type UnregisterOption

type UnregisterOption func(*unregisterOptions)

UnregisterOption sets an optional field of an alias unregistration.

func WithUnregisterReason

func WithUnregisterReason(reason string) UnregisterOption

WithUnregisterReason attaches a reason. It is sent in the body but, matching the API contract, it does not enter the checksum.

type ValidationError

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

ValidationError is returned when an argument or request field is invalid. Its message is identical to the one the PHP SDK raises.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements error.

func (*ValidationError) Is

func (e *ValidationError) Is(target error) bool

Is reports whether the error matches ErrInvalidArgument.

Directories

Path Synopsis
internal
php
Package php reproduces the PHP semantics that the dpay wire protocol depends on.
Package php reproduces the PHP semantics that the dpay wire protocol depends on.
wire
Package wire carries the dpay protocol mechanics: ordered request bodies, checksums and API host resolution.
Package wire carries the dpay protocol mechanics: ordered request bodies, checksums and API host resolution.

Jump to

Keyboard shortcuts

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