package module
Version: v0.3.4 Latest Latest

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

Go to latest
Published: Nov 24, 2022 License: MPL-2.0 Imports: 16 Imported by: 0



This Go package implements the new JSON based Datatrans API #golang #paymentprovider



	c, err := datatrans.MakeClient(
			InternalID: "",
			EnableProduction: true,
			EnableIdempotency: true,
			MerchantID: "32234323242",
			Password:   "dbce0e6cfc012e475c843c1bbb0ca439a048fe8e",
		// add more merchants if you like
			InternalID: "B",
			EnableProduction: false,
			MerchantID: "78967896789",
			Password:   "e249002bc8e0c36dd89c393bfc7f7aa369c5842f",
	// uses the merchant B
	bc := c.WithMerchant("B")
	// uses default merchant
My request needs additional fields which aren't in the struct!

How can I extend the JSON data posted to datatrans?

	ri := &datatrans.RequestInitialize{
		Currency:   "CHF",
		RefNo:      "234234",
		AutoSettle: true,
		Amount:     10023,
		Language:   "DE",
		CustomFields: map[string]interface{}{
			"TWI": map[string]interface{}{
				"alias": "ZGZhc2RmYXNkZmFzZGZhc2Q=",
	data, err := datatrans.MarshalJSON(ri)
	// handle error
	// using TWI for Twint specific parameters
	const wantJSON = `{"TWI":{"alias":"ZGZhc2RmYXNkZmFzZGZhc2Q="},"amount":10023,"autoSettle":true,"currency":"CHF","language":"DE","refno":"234234"}`
	if string(data) != wantJSON {
		t.Errorf("\nWant: %s\nHave: %s", wantJSON, data)
I need a custom http.Client

	c, err := datatrans.MakeClient(
			Timeout: 30*time.Second,
			InternalID: "",
			EnableProduction: true,
			EnableIdempotency: true,
			MerchantID: "32234323242",
			Password:   "dbce0e6cfc012e475c843c1bbb0ca439a048fe8e",


Mozilla Public License Version 2.0




This section is empty.


View Source
var (
	ErrWebhookMissingSignature  = errors.New("malformed header Datatrans-Signature")
	ErrWebhookMismatchSignature = errors.New("mismatch of Datatrans-Signature")


func MarshalJSON

func MarshalJSON(postData interface{}) ([]byte, error)

MarshalJSON encodes the postData struct to json but also can merge custom settings into the final JSON. This function is called before sending the request to datatrans. Function exported for debug reasons.

func ValidateWebhook

func ValidateWebhook(wo WebhookOption) (func(next http.Handler) http.Handler, error)

ValidateWebhook an HTTP middleware which checks that the signature in the header is valid.


type CardAlias

type CardAlias struct {
	Alias          string `json:"alias,omitempty"`
	ExpiryMonth    string `json:"expiryMonth,omitempty"`
	ExpiryYear     string `json:"expiryYear,omitempty"`
	CreateAliasCVV bool   `json:"createAliasCVV,omitempty"` // only used when initializing a transaction

type CardExtended

type CardExtended struct {
	Alias           string            `json:"alias,omitempty"`
	AliasCVV        string            `json:"aliasCVV,omitempty"`
	Masked          string            `json:"masked,omitempty"`
	ExpiryMonth     string            `json:"expiryMonth,omitempty"`
	ExpiryYear      string            `json:"expiryYear,omitempty"`
	Info            *CardExtendedInfo `json:"info,omitempty"`
	WalletIndicator string            `json:"walletIndicator,omitempty"`

type CardExtendedInfo

type CardExtendedInfo struct {
	Brand   string `json:"brand,omitempty"`
	Type    string `json:"type,omitempty"`
	Usage   string `json:"usage,omitempty"`
	Country string `json:"country,omitempty"`
	Issuer  string `json:"issuer,omitempty"`

type CardMaskedSimple

type CardMaskedSimple struct {
	Masked string `json:"masked,omitempty"`

type Client

type Client struct {
	// contains filtered or unexported fields

func MakeClient

func MakeClient(opts ...Option) (Client, error)

func (*Client) AliasConvert

func (c *Client) AliasConvert(ctx context.Context, legacyAlias string) (string, error)

AliasConvert converts a legacy (numeric or masked) alias to the most recent alias format.

func (*Client) AliasDelete

func (c *Client) AliasDelete(ctx context.Context, alias string) error

AliasDelete deletes an alias with immediate effect. The alias will no longer be recognized if used later with any API call.

func (*Client) Authorize

func (c *Client) Authorize(ctx context.Context, rva RequestAuthorize) (*ResponseCardMasked, error)

Authorize a transaction. Use this API to make an authorization without user interaction. (For example merchant initiated transactions with an alias) Depending on the payment method, different parameters are mandatory. Refer to the payment method specific objects (for example PAP) to see which parameters so send. For credit cards, the card object can be used.

func (*Client) AuthorizeTransaction

func (c *Client) AuthorizeTransaction(ctx context.Context, transactionID string, rva RequestAuthorizeTransaction) (*ResponseAuthorize, error)

AuthorizeTransaction an authenticated transaction. If during the initialization of a transaction the parameter option.authenticationOnly was set to true, this API can be used to authorize an already authenticated (3D) transaction.

func (*Client) Cancel

func (c *Client) Cancel(ctx context.Context, transactionID string, refno string) error

Cancel API can be used to release the blocked amount from an authorization. The transaction must either be in status authorized or settled. The transactionId is needed to cancel an authorization.

func (*Client) Credit

func (c *Client) Credit(ctx context.Context, transactionID string, rc RequestCredit) (*ResponseCardMasked, error)

Credit uses the credit API to credit a transaction which is in status settled. The previously settled amount must not be exceeded.

func (*Client) CreditAuthorize

func (c *Client) CreditAuthorize(ctx context.Context, rca RequestCreditAuthorize) (*ResponseCardMasked, error)

CreditAuthorize allows to use this API to make a credit without referring to a previous authorization. This can be useful if you want to credit a cardholder when there was no debit.

func (*Client) GetDataInt added in v0.3.2

func (c *Client) GetDataInt(key string) (int, bool)

GetDataInt returns the int value from the data map or false if not found or failed to convert.

func (*Client) GetDataRaw added in v0.3.2

func (c *Client) GetDataRaw(key string) (interface{}, bool)

func (*Client) GetDataString added in v0.3.2

func (c *Client) GetDataString(key string) (string, bool)

GetDataString returns the string value from the data map or false if not found or failed to convert.

func (*Client) Initialize

func (c *Client) Initialize(ctx context.Context, rva RequestInitialize) (*ResponseInitialize, error)

Initialize a transaction. Securely send all the needed parameters to the transaction initialization API. The result of this API call is a HTTP 201 status code with a transactionId in the response body and the Location header set. If you want to use the payment page redirect mode to collect the payment details, the browser needs to be redirected to this URL to continue with the transaction. Following the link provided in the Location header will raise the Datatrans Payment Page with all the payment methods available for the given merchantId. If you want to limit the number of payment methods, the paymentMethod array can be used.

func (*Client) ReconciliationsSales

func (c *Client) ReconciliationsSales(ctx context.Context, sale RequestReconciliationsSale) (*ResponseReconciliationsSale, error)

ReconciliationsSales reports a sale. When using reconciliation, use this API to report a sale. The matching is based on the transactionId.

func (*Client) ReconciliationsSalesBulk

func (c *Client) ReconciliationsSalesBulk(ctx context.Context, sales RequestReconciliationsSales) (*ResponseReconciliationsSales, error)

ReconciliationsSalesBulk reports bulk sales. When using reconciliation, use this API to report multiples sales with a single API call. The matching is based on the transactionId.

func (*Client) SecureFieldsInit

func (c *Client) SecureFieldsInit(ctx context.Context, rva RequestSecureFieldsInit) (*ResponseInitialize, error)

InitializeSecureFields initializes a Secure Fields transaction. Proceed with the steps below to process Secure Fields payment transactions.

func (*Client) SecureFieldsUpdate

func (c *Client) SecureFieldsUpdate(ctx context.Context, transactionID string, rva RequestSecureFieldsUpdate) error

SecureFieldsUpdate use this API to update the amount of a Secure Fields transaction. This action is only allowed before the 3D process. At least one property must be updated.

func (*Client) Settle

func (c *Client) Settle(ctx context.Context, transactionID string, rs RequestSettle) error

Settle request is often also referred to as “Capture” or “Clearing”. It can be used for the settlement of previously authorized transactions. The transactionId is needed to settle an authorization. Note: This API call is not needed if "autoSettle": true was used when initializing a transaction.

func (*Client) Status

func (c *Client) Status(ctx context.Context, transactionID string) (*ResponseStatus, error)

Status allows once a transactionId has been received the status can be checked with the Status API.

func (*Client) ValidateAlias

func (c *Client) ValidateAlias(ctx context.Context, rva RequestValidateAlias) (*ResponseCardMasked, error)

ValidateAlias an existing alias can be validated at any time with the transaction validate API. No amount will be blocked on the customers account. Only credit cards (including Apple Pay and Google Pay), PFC, KLN and PAP support validation of an existing alias.

func (*Client) WithMerchant

func (c *Client) WithMerchant(internalID string) *Client

WithMerchant sets an ID and returns a shallow clone of the client.

type CustomFields

type CustomFields map[string]interface{}

CustomFields allows to extend any input with merchant specific settings.

type Customer

type Customer struct {
	ID                    string `json:"id,omitempty"`                    // Unique customer identifier
	Title                 string `json:"title,omitempty"`                 // Something like Ms or Mrs
	FirstName             string `json:"firstName,omitempty"`             // The first name of the customer.
	LastName              string `json:"lastName,omitempty"`              // The last name of the customer.
	Street                string `json:"street,omitempty"`                // The street of the customer.
	Street2               string `json:"street2,omitempty"`               // Additional street information. For example: '3rd floor'
	City                  string `json:"city,omitempty"`                  // The city of the customer.
	Country               string `json:"country,omitempty"`               // 2 letter ISO 3166-1 alpha-2 country code
	ZipCode               string `json:"zipCode,omitempty"`               // Zip code of the customer.
	Phone                 string `json:"phone,omitempty"`                 // Phone number of the customer.
	CellPhone             string `json:"cellPhone,omitempty"`             // Cell Phone number of the customer.
	Email                 string `json:"email,omitempty"`                 // The email address of the customer.
	Gender                string `json:"gender,omitempty"`                // Gender of the customer. female or male.
	BirthDate             string `json:"birthDate,omitempty"`             // The birth date of the customer. Must be in ISO-8601 format (YYYY-MM-DD).
	Language              string `json:"language,omitempty"`              // The language of the customer.
	Type                  string `json:"type,omitempty"`                  // P or C depending on whether the customer is private or a company. If C, the fields name and companyRegisterNumber are required
	Name                  string `json:"name,omitempty"`                  // The name of the company. Only applicable if type=C
	CompanyLegalForm      string `json:"companyLegalForm,omitempty"`      // The legal form of the company (AG, GmbH, ...)
	CompanyRegisterNumber string `json:"companyRegisterNumber,omitempty"` // The register number of the company. Only applicable if type=C
	IpAddress             string `json:"ipAddress,omitempty"`             // The ip address of the customer.

type ErrorDetail

type ErrorDetail struct {
	Code    string `json:"code"`
	Message string `json:"message"`


type ErrorResponse

type ErrorResponse struct {
	HTTPStatusCode int
	ErrorDetail    ErrorDetail `json:"error"`

func (ErrorResponse) Error

func (s ErrorResponse) Error() string

type History

type History struct {
	Action  string    `json:"action,omitempty"`
	Amount  int       `json:"amount,omitempty"`
	Source  string    `json:"source,omitempty"`
	Date    time.Time `json:"date,omitempty"`
	Success bool      `json:"success,omitempty"`
	IP      string    `json:"ip,omitempty"`

type InitializeOption

type InitializeOption struct {
	// Whether an alias should be created for this transaction or not. If set to
	// true an alias will be created. This alias can then be used to initialize
	// or authorize a transaction. One possible use case is to charge the card of
	// an existing (registered) cardholder.
	CreateAlias            bool   `json:"createAlias"`
	ReturnMaskedCardNumber bool   `json:"returnMaskedCardNumber"` // Whether to return the masked card number. Format: 520000xxxxxx0080
	ReturnCustomerCountry  bool   `json:"returnCustomerCountry"`  // If set to true, the country of the customers issuer will be returned.
	AuthenticationOnly     bool   `json:"authenticationOnly"`     // Whether to only authenticate the transaction (3D process only). If set to true, the actual authorization will not take place.
	RememberMe             string `json:"rememberMe"`             // Enum: "true" "checked"	Whether to show a checkbox on the payment page to let the customer choose if they want to save their card information.
	ReturnMobileToken      bool   `json:"returnMobileToken"`      // Indicates that a mobile token should be created. This is needed when using our Mobile SDKs.

type Option

type Option interface {
	// contains filtered or unexported methods

type OptionHTTPRequestFn

type OptionHTTPRequestFn func(req *http.Request) (*http.Response, error)

type OptionMerchant

type OptionMerchant struct {
	InternalID       string
	EnableProduction bool
	// If your request failed to reach our servers, no idempotent result is saved
	// because no API endpoint processed your request. In such cases, you can
	// simply retry your operation safely. Idempotency keys remain stored for 3
	// minutes. After 3 minutes have passed, sending the same request together
	// with the previous idempotency key will create a new operation.
	EnableIdempotency  bool
	DisableRawJSONBody bool
	MerchantID         string // basic auth user
	Password           string // basic auth pw
	// Data contains merchant specific other IDs or configurations. Keys/Values
	// from this map are not getting used in requests towards datatrans.
	Data map[string]interface{}

type RawJSONBody

type RawJSONBody []byte

RawJSONBody includes the original response from the datatrans server. There might be custom fields in the response which are not included in the structs in this package. This type allows for unmarshaling into custom structs.

type Redirect

type Redirect struct {
	SuccessUrl string `json:"successUrl,omitempty"` // The URL where the customer gets redirected to if the transaction was successful.
	CancelUrl  string `json:"cancelUrl,omitempty"`  // The URL where the customer gets redirected to if the transaction was canceled.
	ErrorUrl   string `json:"errorUrl,omitempty"`   // The URL where the customer gets redirected to if an error occurred.
	// If the payment is started within an iframe or when using the Lightbox
	// Mode, use value _top. This ensures a proper browser flow for payment
	// methods who need a redirect.
	StartTarget string `json:"startTarget,omitempty"`
	// If the payment is started within an iframe or when using the Lightbox
	// Mode, use _top if the redirect URLs should be opened full screen when
	// payment returns from a 3rd party (for example 3D).
	ReturnTarget string `json:"returnTarget,omitempty"`
	// The preferred HTTP method for the redirect request (GET or POST). When
	// using GET as a method, the query string parameter datatransTrxId will be
	// added to the corresponding return url upon redirection. In case of POST,
	// all the query parameters from the corresponding return url will be moved
	// to the application/x-www-form-urlencoded body of the redirection request
	// along with the added datatransTrxId parameter.
	Method string `json:"method,omitempty"` // Default: "GET"	Enum: "GET" "POST"

type RequestAuthorize

type RequestAuthorize struct {
	Amount     int    `json:"amount,omitempty"`
	Currency   string `json:"currency,omitempty"`
	RefNo      string `json:"refno,omitempty"`
	RefNo2     string `json:"refno2,omitempty"`
	AutoSettle bool   `json:"autoSettle,omitempty"`
	// The card object to be submitted when authorizing with an existing credit
	// card alias.
	Card         *CardAlias `json:"card,omitempty"`
	CustomFields `json:"-"`

type RequestAuthorizeTransaction

type RequestAuthorizeTransaction struct {
	RefNo        string `json:"refno,omitempty"`
	Amount       int    `json:"amount,omitempty"`
	AutoSettle   bool   `json:"autoSettle,omitempty"`
	RefNo2       string `json:"refno2,omitempty"`
	CustomFields `json:"-"`

type RequestCredit

type RequestCredit struct {
	Amount       int    `json:"amount,omitempty"`
	Currency     string `json:"currency,omitempty"`
	RefNo        string `json:"refno,omitempty"`
	RefNo2       string `json:"refno2,omitempty"`
	CustomFields `json:"-"`

type RequestCreditAuthorize

type RequestCreditAuthorize struct {
	Currency     string     `json:"currency,omitempty"`
	RefNo        string     `json:"refno,omitempty"`
	Card         *CardAlias `json:"card,omitempty"`
	Amount       int        `json:"amount,omitempty"`
	AutoSettle   bool       `json:"autoSettle,omitempty"`
	Refno2       string     `json:"refno2,omitempty"`
	CustomFields `json:"-"`

type RequestInitialize

type RequestInitialize struct {
	Currency       string            `json:"currency"`
	RefNo          string            `json:"refno"`
	RefNo2         string            `json:"refno2,omitempty"`
	AutoSettle     bool              `json:"autoSettle,omitempty"`
	Customer       *Customer         `json:"customer,omitempty"`
	Card           *CardAlias        `json:"card,omitempty"`
	Amount         int               `json:"amount,omitempty"`
	Language       string            `json:"language,omitempty"` // Enum: "en" "de" "fr" "it" "es" "el" "no" "da" "pl" "pt" "ru" "ja"
	PaymentMethods []string          `json:"paymentMethods,omitempty"`
	Theme          *Theme            `json:"theme,omitempty"`
	Redirect       *Redirect         `json:"redirect,omitempty"`
	Option         *InitializeOption `json:"option,omitempty"`
	CustomFields   `json:"-"`

type RequestReconciliationsSale

type RequestReconciliationsSale struct {
	Date          time.Time `json:"date"`
	TransactionID string    `json:"transactionId"`
	Currency      string    `json:"currency"`
	Amount        int       `json:"amount"`
	Type          string    `json:"type"`
	Refno         string    `json:"refno"`

type RequestReconciliationsSales

type RequestReconciliationsSales struct {
	Sales []RequestReconciliationsSale `json:"sales"`

type RequestSecureFieldsInit

type RequestSecureFieldsInit struct {
	Currency     string `json:"currency"`
	Amount       int    `json:"amount,omitempty"`
	ReturnUrl    string `json:"returnUrl"`
	CustomFields `json:"-"`

type RequestSecureFieldsUpdate

type RequestSecureFieldsUpdate struct {
	Currency     string `json:"currency"`
	Amount       int    `json:"amount,omitempty"`
	CustomFields `json:"-"`

type RequestSettle

type RequestSettle struct {
	Amount       int    `json:"amount,omitempty"`
	Currency     string `json:"currency,omitempty"`
	RefNo        string `json:"refno,omitempty"`
	RefNo2       string `json:"refno2,omitempty"`
	CustomFields `json:"-"`

type RequestValidateAlias

type RequestValidateAlias struct {
	Currency     string     `json:"currency,omitempty"`
	RefNo        string     `json:"refno,omitempty"`
	RefNo2       string     `json:"refno2,omitempty"`
	Card         *CardAlias `json:"card,omitempty"`
	CustomFields `json:"-"`

type ResponseAuthorize

type ResponseAuthorize struct {
	AcquirerAuthorizationCode string `json:"acquirerAuthorizationCode"`
	RawJSONBody               `json:"raw,omitempty"`

type ResponseCardMasked

type ResponseCardMasked struct {
	TransactionId             string            `json:"transactionId,omitempty"`
	AcquirerAuthorizationCode string            `json:"acquirerAuthorizationCode,omitempty"`
	Card                      *CardMaskedSimple `json:"card,omitempty"` // only set in case of CreditAuthorize
	RawJSONBody               `json:"raw,omitempty"`

type ResponseInitialize

type ResponseInitialize struct {
	Location      string `json:"location,omitempty"` // A URL where the users browser needs to be redirect to complete the payment. This redirect is only needed when using Redirect Mode. For Lightbox Mode the returned transactionId can be used to start the payment page.
	TransactionId string `json:"transactionId,omitempty"`
	MobileToken   string `json:"mobileToken,omitempty"`
	RawJSONBody   `json:"raw,omitempty"`

type ResponseReconciliationsSale

type ResponseReconciliationsSale struct {
	TransactionID string    `json:"transactionId"`
	SaleDate      time.Time `json:"saleDate"`
	ReportedDate  time.Time `json:"reportedDate"`
	MatchResult   string    `json:"matchResult"`

type ResponseReconciliationsSales

type ResponseReconciliationsSales struct {
	Sales []ResponseReconciliationsSale `json:"sales"`

type ResponseStatus

type ResponseStatus struct {
	TransactionID string `json:"transactionId,omitempty"`
	MerchantID    string `json:"merchantId,omitempty"`
	Type          string `json:"type,omitempty"`
	Status        string `json:"status,omitempty"`
	Currency      string `json:"currency,omitempty"`
	RefNo         string `json:"refno,omitempty"`
	PaymentMethod string `json:"paymentMethod,omitempty"`
	Detail        struct {
		Init struct {
			Expires time.Time `json:"expires,omitempty"` // Tells when the initialized transaction will expire if not continued - 30 minutes after initialization.
		} `json:"init,omitempty"`
		Authorize struct {
			Amount                    int    `json:"amount,omitempty"`
			AcquirerAuthorizationCode string `json:"acquirerAuthorizationCode,omitempty"`
		} `json:"authorize,omitempty"`
		Settle struct {
			Amount int `json:"amount,omitempty"`
		} `json:"settle,omitempty"`
		Credit struct {
			Amount int `json:"amount,omitempty"`
		} `json:"credit,omitempty"`
		Cancel struct {
			Reversal bool `json:"reversal,omitempty"` // Whether the transaction was reversed on acquirer side.
		} `json:"cancel,omitempty"`
		Fail struct {
			Reason  string `json:"reason,omitempty"`
			Message string `json:"message,omitempty"`
		} `json:"fail,omitempty"`
	} `json:"detail,omitempty"`
	Customer    *Customer     `json:"customer,omitempty"`
	Card        *CardExtended `json:"card,omitempty"`
	Language    string        `json:"language,omitempty"`
	History     []History     `json:"history,omitempty"`
	RawJSONBody `json:"raw,omitempty"`

type Theme

type Theme struct {
	// 	Theme configuration options when using the default DT2015 theme
	Name          string             `json:"name,omitempty"` // Theme name, e.g. DT2015
	Configuration ThemeConfiguration `json:"configuration,omitempty"`

type ThemeConfiguration

type ThemeConfiguration struct {
	BrandColor         string `json:"brandColor,omitempty"`         // Hex notation of a color
	TextColor          string `json:"textColor,omitempty"`          // Enum: "white" "black"	The color of the text in the header bar if no logo is given
	LogoType           string `json:"logoType,omitempty"`           // Enum: "circle" "rectangle" "none" 	The header logo's display style
	LogoBorderColor    string `json:"logoBorderColor,omitempty"`    // Decides whether the logo shall be styled with a border around it, if the value is true the default background color is chosen, else the provided string is used as color value
	BrandButton        string `json:"brandButton,omitempty"`        // Decides if the pay button should have the same color as the brandColor. If set to false the hex color #01669F will be used as a default
	PayButtonTextColor string `json:"payButtonTextColor,omitempty"` // The color (hex) of the pay button
	LogoSrc            string `json:"logoSrc,omitempty"`            // An SVG image provided by the merchant. The image needs to be uploaded by using the Datatrans Web Administration Tool
	InitialView        string `json:"initialView,omitempty"`        // Enum: "list" "grid"	Wheter the payment page shows the payment method selection as list (default) or as a grid
	BrandTitle         bool   `json:"brandTitle,omitempty"`         // If set to false and no logo is used (see logoSrc), the payment page header will be empty

type WebhookOption

type WebhookOption struct {
	Sign2HMACKey string                   // hex encoded
	ErrorHandler func(error) http.Handler // optional custom error handler

Jump to

Keyboard shortcuts

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