twikey

package module
v0.1.12 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2022 License: MIT Imports: 19 Imported by: 0

README

Twikey API client for Go

Want to allow your customers to pay in the most convenient way, then Twikey is right what you need.

Recurring or occasional payments via (Recurring) Credit Card, SEPA Direct Debit or any other payment method by bringing your own payment service provider or by leveraging your bank contract.

Twikey offers a simple and safe multichannel solution to negotiate and collect recurring (or even occasional) payments. Twikey has integrations with a lot of accounting and CRM packages. It is the first and only provider to operate on a European level for Direct Debit and can work directly with all major Belgian and Dutch Banks. However you can use the payment options of your favorite PSP to allow other customers to pay as well.

Requirements

Go Reference Go Report Card

To use the Twikey API client, the following things are required:

  • Get yourself a Twikey account.
  • Go >= 1.6
  • Up-to-date OpenSSL (or other SSL/TLS toolkit)

Installation

The easiest way to install the Twikey API client is with go get

$  go get -u github.com/twikey/twikey-api-go 

How to create anything

The api works the same way regardless if you want to create a mandate, a transaction, an invoice or even a paylink. the following steps should be implemented:

  1. Use the Twikey API client to create or import your item.

  2. Once available, our platform will send an asynchronous request to the configured webhook to allow the details to be retrieved. As there may be multiple items ready for you a "feed" endpoint is provided which acts like a queue that can be read until empty till the next time.

  3. The customer returns, and should be satisfied to see that the action he took is completed.

Find our full documentation online on api.twikey.com.

Getting started

Initializing the Twikey API client by configuring your API key which you can find in the Twikey merchant interface.

import (
    twikey "github.com/twikey/twikey-api-go"
)

var twikeyClient = twikey.NewClient(os.Getenv("TWIKEY_API_KEY"))

var twikeyClient = &twikey.TwikeyClient{
    ApiKey:  os.Getenv("TWIKEY_API_KEY"),
    //Debug: log.Default(),
    HTTPClient: &http.Client{
        Timeout: time.Minute,
    },
}

Documents

Invite a customer to sign a SEPA mandate using a specific behaviour template (ct) that allows you to configure the behaviour or flow that the customer will experience. This 'ct' can be found in the template section of the settings. The extra can be used to pass in extra attributes linked to the mandate.

invite, err := twikeyClient.DocumentInvite(&InviteRequest{
   ct:             yourct,
   customerNumber: "123",
   email:          "john@doe.com",
   firstname:      "John",
   lastname:       "Doe",
   l:              "en",
   address:        "Abbey road",
   city:           "Liverpool",
   zip:            "1526",
   country:        "BE",
}, nil)
if err != nil {
    t.Fatal(err)
}
fmt.println(invite.Url)

After creation, the link available in invite.Url can be used to redirect the customer into the signing flow or even send him a link through any other mechanism. Ideally you store the mandatenumber for future usage (eg. sending transactions).

The DocumentSign function has a similar syntax only that it requires a method and is mosly used for interactive sessions where no screens are involved. See the documentation for more info.

Feed

Once signed, a webhook is sent (see below) after which you can fetch the detail through the document feed, which you can actually think of as reading out a queue. Since it'll return you the changes since the last time you called it.

err := c.DocumentFeed(func(mandate *Mndt, eventTime string) {
    fmt.println("Document created   ", mandate.MndtId, " @ ", eventTime)
}, func(originalMandateNumber string, mandate *Mndt, reason *AmdmntRsn, eventTime string) {
    fmt.println("Document updated   ", originalMandateNumber, reason.Rsn, " @ ", eventTime)
}, func(mandateNumber string, reason *CxlRsn, eventTime string) {
    fmt.println("Document cancelled ", mandateNumber, reason.Rsn, " @ ", eventTime)
})

Transactions

Send new transactions and act upon feedback from the bank.

tx, err := twikeyClient.TransactionNew(&TransactionRequest{
   DocumentReference: "ABC",
   Msg:               "My Transaction",
   Ref:               "My Reference",
   Amount:            10.90,
})
fmt.println("New tx", tx)

Feed

err := twikeyClient.TransactionFeed(func(transaction *Transaction) {
    fmt.println("Transaction", transaction.Amount, transaction.BookedError, transaction.Final)
})

Webhook

When wants to inform you about new updates about documents or payments a webhookUrl specified in your api settings be called.

err := twikeyClient.verifyWebhook("55261CBC12BF62000DE1371412EF78C874DBC46F513B078FB9FF8643B2FD4FC2", "abc=123&name=abc")
if err != nil {
    t.Fatal(err)
}

API documentation

If you wish to learn more about our API, please visit the Twikey Api Page. API Documentation is available in English.

Want to help us make our API client even better?

Want to help us make our API client even better? We take pull requests.

Support

Contact: www.twikey.com

Documentation

Overview

Package twikey provides the bindings for Twikey REST APIs.

Index

Constants

This section is empty.

Variables

View Source
var SystemError error = &TwikeyError{
	Status: 500,
	Code:   "system_error",
}

Functions

This section is empty.

Types

type AmdmntRsn

type AmdmntRsn struct {
	Rsn string
}

AmdmntRsn contains the reason why something was updated

type Client

type Client struct {
	BaseURL    string
	APIKey     string
	PrivateKey string
	Salt       string
	UserAgent  string
	HTTPClient HTTPClient
	Debug      *log.Logger
	// contains filtered or unexported fields
}

Client is the base class, please use a dedicated UserAgent so we can notify the emergency contact if weird behaviour is perceived.

func NewClient

func NewClient(apiKey string) *Client

NewClient is a convenience method to hit the ground running with the Twikey Rest API

func (*Client) CustomerUpdate added in v0.1.6

func (c *Client) CustomerUpdate(request *Customer) error

func (*Client) DocumentCancel

func (c *Client) DocumentCancel(mandate string, reason string) error

DocumentCancel allows to cancel (or delete if unsigned) a previously added document

func (*Client) DocumentDetail added in v0.1.2

func (c *Client) DocumentDetail(mndtId string) (*Mndt, error)

DocumentDetail allows a snapshot of a particular mandate, note that this is rate limited

func (*Client) DocumentFeed

func (c *Client) DocumentFeed(
	newDocument func(mandate *Mndt, eventTime string),
	updateDocument func(originalMandateNumber string, mandate *Mndt, reason *AmdmntRsn, eventTime string),
	cancelledDocument func(mandateNumber string, reason *CxlRsn, eventTime string)) error

DocumentFeed retrieves all documents since the last call with callbacks since there may be many

func (*Client) DocumentInvite

func (c *Client) DocumentInvite(request *InviteRequest) (*Invite, error)

DocumentInvite allows to invite a customer to sign a specific document

func (*Client) DocumentSign added in v0.1.4

func (c *Client) DocumentSign(request *InviteRequest) (*Invite, error)

DocumentSign allows a customer to sign directly a specific document

func (*Client) DocumentUpdate

func (c *Client) DocumentUpdate(request *UpdateRequest) error

DocumentUpdate allows to update a previously added document

func (*Client) DownloadPdf

func (c *Client) DownloadPdf(mndtId string, downloadFile string) error

DownloadPdf allows the download of a specific (signed) pdf

func (*Client) InvoiceAdd added in v0.1.2

func (c *Client) InvoiceAdd(ctx context.Context, invoice *Invoice) (*Invoice, error)

InvoiceFromUbl sends an invoice to Twikey in UBL format

func (*Client) InvoiceFeed

func (c *Client) InvoiceFeed(callback func(invoice *Invoice), sideloads ...string) error

InvoiceFeed Get invoice Feed twikey

func (*Client) InvoiceFromUbl

func (c *Client) InvoiceFromUbl(ctx context.Context, ublBytes []byte, ref string, noAutoCollection bool) (*Invoice, error)

InvoiceFromUbl sends an invoice to Twikey in UBL format

func (*Client) PaylinkFeed

func (c *Client) PaylinkFeed(callback func(paylink *Paylink), sideloads ...string) error

PaylinkFeed retrieves the feed of updated paylinks since last call

func (*Client) PaylinkNew

func (c *Client) PaylinkNew(paylinkRequest *PaylinkRequest) (*Paylink, error)

PaylinkNew sends the new paylink to Twikey for creation

func (*Client) Ping added in v0.1.7

func (c *Client) Ping() error

Ping Try the current credentials

func (*Client) ReservationNew added in v0.1.4

func (c *Client) ReservationNew(transaction *TransactionRequest) (*Reservation, error)

ReservationNew sends a new reservation to Twikey

func (*Client) TransactionCollect added in v0.1.11

func (c *Client) TransactionCollect(template string, prenotify bool) (string, error)

TransactionCollect collects all open transaction

func (*Client) TransactionFeed

func (c *Client) TransactionFeed(callback func(transaction *Transaction), sideloads ...string) error

TransactionFeed retrieves all transaction updates since the last call with a callback since there may be many

func (*Client) TransactionNew

func (c *Client) TransactionNew(transaction *TransactionRequest) (*Transaction, error)

TransactionNew sends a new transaction to Twikey

func (*Client) VerifyWebhook

func (c *Client) VerifyWebhook(signatureHeader string, payload string) error

VerifyWebhook allows the verification of incoming webhooks.

type CollectResponse added in v0.1.11

type CollectResponse struct {
	ID string `json:"rcurMsgId"`
}

CollectResponse is a struct to contain the response coming from Twikey, should be considered internal

type CtctDtls

type CtctDtls struct {
	EmailAdr string
	MobNb    string
	Othr     string
}

CtctDtls contains all contact details for a specific document

type Customer

type Customer struct {
	CustomerNumber string `json:"customerNumber,omitempty"`
	Email          string `json:"email,omitempty"`
	CompanyName    string `json:"companyName"`
	Coc            string `json:"coc"`
	FirstName      string `json:"firstName"`
	LastName       string `json:"lastName"`
	Address        string `json:"address"`
	City           string `json:"city"`
	Zip            string `json:"zip"`
	Country        string `json:"country"`
	Language       string `json:"l"`
	Mobile         string `json:"mobile,omitempty"`
}

Customer is a json wrapper for usage inside the Invoice object

type CxlRsn

type CxlRsn struct {
	Rsn string
}

CxlRsn contains the reason why something was cancelled

type DbtrAgt

type DbtrAgt struct {
	FinInstnId FinInstnId
}

type FinInstnId

type FinInstnId struct {
	BICFI string
}

type HTTPClient added in v0.1.3

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

type Invite

type Invite struct {
	MndtId string // documentNumber
	Url    string // where the customer can sign the document
	Key    string // specific invite key
}

Invite is the response containing the documentNumber, key and the url to point the customer too.

type InviteRequest

type InviteRequest struct {
	Template       string // mandatory
	CustomerNumber string
	Email          string
	Mobile         string
	Language       string
	Lastname       string
	Firstname      string
	MandateNumber  string
	ContractNumber string
	CompanyName    string
	Coc            string
	Address        string
	City           string
	Zip            string
	Country        string
	SignDate       string
	Amount         string
	Iban           string
	Bic            string
	Campaign       string
	Method         string
	Extra          map[string]string
}

InviteRequest contains all possible parameters that can be send to invite a customer to sign a document

func (*InviteRequest) Add added in v0.1.6

func (request *InviteRequest) Add(key string, value string)

type Invoice

type Invoice struct {
	Id                 string           `json:"id,omitempty"`
	Number             string           `json:"number"`
	Title              string           `json:"title"`
	Remittance         string           `json:"remittance"`
	Ct                 int              `json:"ct,omitempty"`
	Manual             bool             `json:"manual,omitempty"`
	State              string           `json:"state,omitempty"`
	Amount             float64          `json:"amount"`
	Date               string           `json:"date"`
	Duedate            string           `json:"duedate"`
	Ref                string           `json:"ref,omitempty"`
	CustomerByDocument string           `json:"customerByDocument,omitempty"`
	Customer           *Customer        `json:"customer,omitempty"`
	Pdf                []byte           `json:"pdf,omitempty"`
	Meta               *InvoiceFeedMeta `json:"meta,omitempty"`
	LastPayment        *Lastpayment     `json:"lastpayment,omitempty"`
}

Invoice is the base object for sending and receiving invoices to Twikey

func (*Invoice) HasMeta

func (inv *Invoice) HasMeta() bool

HasMeta convenience method to indicate that there is extra info available on the invoice

func (*Invoice) IsFailed

func (inv *Invoice) IsFailed() bool

IsFailed allows to distinguish invoices since they go from pending to booked or expired when payment failed

func (*Invoice) IsPaid

func (inv *Invoice) IsPaid() bool

IsPaid convenience method

type InvoiceFeed

type InvoiceFeed struct {
	Invoices []Invoice
}

InvoiceFeed is a struct to contain the response coming from Twikey, should be considered internal

type InvoiceFeedMeta added in v0.1.3

type InvoiceFeedMeta struct {
	LastError string `json:"lastError,omitempty"`
}

type KeyValue

type KeyValue struct {
	Key   string
	Value interface{}
}

KeyValue key value pairs of extra data in a document

type Lastpayment added in v0.1.9

type Lastpayment []map[string]interface{}

type MandateUpdate

type MandateUpdate struct {
	Mndt        *Mndt
	AmdmntRsn   *AmdmntRsn `json:",omitempty"`
	CxlRsn      *CxlRsn    `json:",omitempty"`
	OrgnlMndtId string
	EvtTime     string
}

MandateUpdate contains all info regarding a new/update or cancelled document

type MandateUpdates

type MandateUpdates struct {
	Messages []MandateUpdate
}

MandateUpdates is a struct to contain the response coming from Twikey, should be considered internal

type Mndt

type Mndt struct {
	MndtId      string
	Dbtr        Prty
	DbtrAcct    string
	DbtrAgt     DbtrAgt
	RfrdDoc     string
	SplmtryData []KeyValue
}

type MndtDetail added in v0.1.2

type MndtDetail struct {
	Mndt Mndt
}
type Paylink struct {
	Id     int64   `json:"id,omitempty"`
	Amount float64 `json:"amount,omitempty"`
	Msg    string  `json:"msg,omitempty"`
	Ref    string  `json:"ref,omitempty"`
	State  string  `json:"state,omitempty"`
	Url    string  `json:"url,omitempty"`
}

Paylink is the response receiving from Twikey upon a request

type PaylinkList struct {
	Links []Paylink
}

type PaylinkRequest

type PaylinkRequest struct {
	CustomerNumber string  //	The customer number (strongly advised)
	Email          string  //	Email of the debtor	(Required to send invite)
	Lastname       string  //	lastname
	Firstname      string  //	firstname
	Language       string  //	Language (en/fr/nl/de/pt/es/it)
	Mobile         string  //	mobile number
	Template       string  //	contract template
	Title          string  //	Message to the debto
	Remittance     string  //	Payment message, if empty then title will be used
	Amount         float64 //	Amount to be billed
	RedirectUrl    string  //	Optional redirect after pay url (must use http(s)://)
	Place          string  //	Optional place
	Expiry         string  //	Optional expiration date
	SendInvite     string  //	Send out invite email or sms directly (email, sms)
	Address        string  //	Address (street + number)
	City           string  //	City of debtor
	Zip            string  //	Zipcode of debtor
	Country        string  //	ISO format (2 letters)
	Txref          string  //	References from existing transactions
	Method         string  //	Circumvents the payment selection with PSP (bancontact/ideal/maestro/mastercard/visa/inghomepay/kbc/belfius)
	Invoice        string  //	create payment link for specific invoice number
	Extra          map[string]string
}

PaylinkRequest is the base object for sending and receiving paylinks to Twikey

func (*PaylinkRequest) Add added in v0.1.6

func (request *PaylinkRequest) Add(key string, value string)

type Prty

type Prty struct {
	Nm       string
	PstlAdr  PstlAdr
	Id       string
	CtctDtls CtctDtls
}

Prty contains party details for a specific document

type PstlAdr

type PstlAdr struct {
	AdrLine string
	PstCd   string
	TwnNm   string
	Ctry    string
}

PstlAdr contains address data for a specific document

type Reservation added in v0.1.4

type Reservation struct {
	Id             string    `json:"id"`
	MndtId         string    `json:"mndtId"`
	ReservedAmount float64   `json:"reservedAmount"`
	Expires        time.Time `json:"expires"`
}

Reservation is the response from Twikey when updates are received

type Transaction

type Transaction struct {
	Id                  int64   `json:"id,omitempty"`
	DocumentId          int64   `json:"contractId,omitempty"`
	DocumentReference   string  `json:"mndtId"`
	Amount              float64 `json:"amount"`
	Message             string  `json:"msg"`
	Ref                 string  `json:"ref"`
	Place               string  `json:"place"`
	Final               bool    `json:"final"`
	State               string  `json:"state"`
	BookedDate          string  `json:"bkdate"`
	BookedError         string  `json:"bkerror"`
	BookedAmount        float64 `json:"bkamount"`
	RequestedCollection string  `json:"reqcolldt"`
}

Transaction is the response from Twikey when updates are received

type TransactionList

type TransactionList struct {
	Entries []Transaction
}

TransactionList is a struct to contain the response coming from Twikey, should be considered internal

type TransactionRequest

type TransactionRequest struct {
	DocumentReference             string
	TransactionDate               string
	RequestedCollection           string
	Msg                           string
	Ref                           string
	Amount                        float64
	Place                         string
	ReferenceIsEndToEndIdentifier bool
	Reservation                   string // via reservation request
	Force                         bool
}

TransactionRequest is the payload to be send to Twikey when a new transaction should be send

type TwikeyError added in v0.1.4

type TwikeyError struct {
	Status  int
	Code    string
	Message string
	Extra   string
}

func NewTwikeyError added in v0.1.4

func NewTwikeyError(code string, msg string, extra string) *TwikeyError

func NewTwikeyErrorFromResponse added in v0.1.4

func NewTwikeyErrorFromResponse(res *http.Response) *TwikeyError

func (*TwikeyError) Error added in v0.1.4

func (err *TwikeyError) Error() string

func (*TwikeyError) IsUserError added in v0.1.4

func (err *TwikeyError) IsUserError() bool

type UpdateRequest

type UpdateRequest struct {
	MandateNumber  string // Document or MandateNumber
	ContractNumber string // ContractNumber
	State          string // active or passive (activated or suspend mandate)
	Mobile         string // Owner's mobile number
	Iban           string // Debtor's IBAN
	Bic            string // Debtor's BIC code
	Email          string // email address of debtor
	Firstname      string // Firstname of the debtor
	Lastname       string // Lastname of the debtor
	CompanyName    string // Company name on the mandate
	Coc            string // The enterprise number (can only be changed if companyName is changed)
	CustomerNumber string // The customer number (can be added, updated or used to move a mandate)
	Language       string // language on the mandate (ISO 2 letters)
	Address        string // Address (street + number)
	City           string // City of debtor
	Zip            string // Zipcode of debtor
	Country        string // Country of debtor
	Extra          map[string]string
}

UpdateRequest contains all possible parameters that can be send to update a document

func (*UpdateRequest) Add added in v0.1.6

func (request *UpdateRequest) Add(key string, value string)

Jump to

Keyboard shortcuts

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