go_klarna

package module
v0.0.0-...-e2f708c Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2023 License: MIT Imports: 9 Imported by: 1

README

go-klarna

Build Status Go Report Card GoDoc

About

This library is an implementation for Klarna payment API in go

How to use

Configuration

Config struct encapsulate the client needs of information

type Config struct {
	BaseURL     *url.URL
	APIUsername string
	APIPassword string
	Timeout     time.Duration
}

Client

Is the abstraction of HTTP client, required by each service in order to operate.

import (
        klarna "github.com/Flaconi/go-klarna"
        "net/url"
        "time"
)

func main() {
        uri, _ := url.Parse(klarna.EuroAPI)
        conf := klarna.Config{
                BaseURL:uri,
                Timeout: time.Second * 10,
        }
        client := klarna.NewClient(conf)
}

Now since we have an instance of the client, we can instantiate any service instance with this client ...

Service

Now, since we have a client, let's instantiate a service

import (
        // ...
)

func main() {
        // previous section ...
        client := klarna.NewClient(conf)

        // payment service
        paymentSrv := klarna.NewPaymentSrv(client)
        err := paymentSrv.CancelExistingAuthorization("string-token")
        if nil != err {
                // do something with the error
        }
}
Road map
  • Implement Checkout API service
  • Cover Checkout API service with tests
  • Implement Payment API service
  • Cover Payment API service with tests
  • Implement Order Management service
  • Cover Order Management service with tests
  • Implement Checkout API Callbacks service
  • Cover Checkout API Callbacks service with tests

Documentation

Index

Constants

View Source
const (

	// Line types
	PhysicalLineType    LineType = "physical"
	DiscountLineType             = "discount"
	ShippingFeeLineType          = "shipping_fee"
	SalesTaxLineType             = "sales_tax"
)
View Source
const (
	EuroAPI = "https://api.klarna.com/"
	UsAPI   = "https://api-na.klarna.com/"
)
View Source
const (
	OrderManagementEndpoint = "/ordermanagement/v1/orders"

	Authorized   = "AUTHORIZED"
	PartCaptured = "PART_CAPTURED"
	Captured     = "CAPTURED"
	Cancelled    = "CANCELLED"
	Expired      = "EXPIRED"
	Closed       = "LOSED"

	Accepted = "ACCEPTED"
	Pending  = "PENDING"
	Rejected = "REJECTED"
)

Variables

View Source
var (
	// ErrOrderCreate error describes that Klarna API is refusing to create the order
	ErrOrderCreate = errors.New("unable to create an order, some fields constraint was violated")
	// ErrUnAuthorized error describes that you are not authorized to perform such an operation
	ErrUnAuthorized = errors.New("You were not unauthorized to execute this operation")
	// ErrReadOnlyResource error describes that the target can not be modified
	ErrReadOnlyResource = errors.New("You tried to modify a read only resource")
	// ErrOrderNotFound error describes that there are no resource found with a provided id
	ErrOrderNotFound = errors.New("No orders found with given ID")
	// ServiceUnavailable error describes any non-classified error response, e.g. 500 status codes
	ServiceUnavailable = errors.New("service temporary unavailable")
)

Functions

This section is empty.

Types

type AdditionalCheckBox

type AdditionalCheckBox struct {
	Text     string `json:"text"`
	Checked  bool   `json:"checked"`
	Required bool   `json:"required"`
}

type Address

type Address struct {
	GivenName      string `json:"given_name,omitempty"`
	FamilyName     string `json:"family_name,omitempty"`
	Email          string `json:"email,omitempty"`
	Title          string `json:"title,omitempty"`
	StreetAddress  string `json:"street_address,omitempty"`
	StreetAddress2 string `json:"street_address2,omitempty"`
	PostalCode     string `json:"postal_code,omitempty"`
	City           string `json:"city,omitempty"`
	Region         string `json:"region,omitempty"`
	Phone          string `json:"phone,omitempty"`
	Country        string `json:"country,omitempty"`
}

Address type define the address object (json serializable) being used for the API to represent billing & shipping addresses

type AdjustAmountLines

type AdjustAmountLines struct {
	AdjustAmount int     `json:"adjust_amount"`
	Description  string  `json:"description,omitempty"`
	OrderLines   []*Line `json:"order_lines,omitempty"`
}

type Attachment

type Attachment struct {
	ContentType string `json:"content_type"`
	Body        string `json:"body"`
}

type Capture

type Capture struct {
	ID              string                       `json:"capture_id,omitempty"`
	KlarnaReference string                       `json:"klarna_reference,omitempty"`
	CaptureAmount   int                          `json:"capture_amount,omitempty"`
	CapturedAt      string                       `json:"captured_at,omitempty"` // DateTime string of ISO 8601
	Description     string                       `json:"description,omitempty"`
	OrderLines      []*Line                      `json:"order_lines,omitempty"`
	RefundedAmount  int                          `json:"refunded_amount,omitempty"`
	BillingAddress  *Address                     `json:"billing_address,omitempty"`
	ShippingAddress *Address                     `json:"shipping_address,omitempty"`
	ShippingInfo    *OrderManagementShippingInfo `json:"shipping_info,omitempty"`
}

type CheckoutCustomer

type CheckoutCustomer struct {
	// DateOfBirth in string representation 2006-01-02
	DateOfBirth string `json:"date_of_birth"`
}

type CheckoutMerchantURLS

type CheckoutMerchantURLS struct {
	// URL of merchant terms and conditions. Should be different than checkout, confirmation and push URLs.
	// (max 2000 characters)
	Terms string `json:"terms"`

	// URL of merchant checkout page. Should be different than terms, confirmation and push URLs.
	// (max 2000 characters)
	Checkout string `json:"checkout"`

	// URL of merchant confirmation page. Should be different than checkout and confirmation URLs.
	// (max 2000 characters)
	Confirmation string `json:"confirmation"`

	// URL that will be requested when an order is completed. Should be different than checkout and
	// confirmation URLs. (max 2000 characters)
	Push string `json:"push"`
	// URL that will be requested for final merchant validation. (must be https, max 2000 characters)
	Validation string `json:"validation,omitempty"`

	// URL for shipping option update. (must be https, max 2000 characters)
	ShippingOptionUpdate string `json:"shipping_option_update,omitempty"`

	// URL for shipping, tax and purchase currency updates. Will be called on address changes.
	// (must be https, max 2000 characters)
	AddressUpdate string `json:"address_update,omitempty"`

	// URL for notifications on pending orders. (max 2000 characters)
	Notification string `json:"notification,omitempty"`

	// URL for shipping, tax and purchase currency updates. Will be called on purchase country changes.
	// (must be https, max 2000 characters)
	CountryChange string `json:"country_change,omitempty"`
}

type CheckoutOptions

type CheckoutOptions struct {
	AcquiringChannel               string              `json:"acquiring_channel,omitempty"`
	AllowSeparateShippingAddress   bool                `json:"allow_separate_shipping_address,omitempty"`
	ColorButton                    string              `json:"color_button,omitempty"`
	ColorButtonText                string              `json:"color_button_text,omitempty"`
	ColorCheckbox                  string              `json:"color_checkbox,omitempty"`
	ColorCheckboxCheckmark         string              `json:"color_checkbox_checkmark,omitempty"`
	ColorHeader                    string              `json:"color_header,omitempty"`
	ColorLink                      string              `json:"color_link,omitempty"`
	DateOfBirthMandatory           bool                `json:"date_of_birth_mandatory,omitempty"`
	ShippingDetails                string              `json:"shipping_details,omitempty"`
	TitleMandatory                 bool                `json:"title_mandatory,omitempty"`
	AdditionalCheckbox             *AdditionalCheckBox `json:"additional_checkbox"`
	RadiusBorder                   string              `json:"radius_border,omitempty"`
	ShowSubtotalDetail             bool                `json:"show_subtotal_detail,omitempty"`
	RequireValidateCallbackSuccess bool                `json:"require_validate_callback_success,omitempty"`
	AllowGlobalBillingCountries    bool                `json:"allow_global_billing_countries,omitempty"`
}

type CheckoutOrder

type CheckoutOrder struct {
	ID                     string                `json:"order_id,omitempty"`
	PurchaseCountry        string                `json:"purchase_country"`
	PurchaseCurrency       string                `json:"purchase_currency"`
	Locale                 string                `json:"locale"`
	Status                 string                `json:"status,omitempty"`
	BillingAddress         *Address              `json:"billing_address,omitempty"`
	ShippingAddress        *Address              `json:"shipping_address,omitempty"`
	OrderAmount            int                   `json:"order_amount"`
	OrderTaxAmount         int                   `json:"order_tax_amount"`
	OrderLines             []*Line               `json:"order_lines"`
	Customer               *CheckoutCustomer     `json:"customer,omitempty"`
	MerchantURLS           *CheckoutMerchantURLS `json:"merchant_urls"`
	HTMLSnippet            string                `json:"html_snippet,omitempty"`
	MerchantReference1     string                `json:"merchant_reference1,omitempty"`
	MerchantReference2     string                `json:"merchant_reference2,omitempty"`
	StartedAt              string                `json:"started_at,omitempty"`
	CompletedAt            string                `json:"completed_at,omitempty"`
	LastModifiedAt         string                `json:"last_modified_at,omitempty"`
	Options                *CheckoutOptions      `json:"options,omitempty"`
	Attachment             *Attachment           `json:"attachment,omitempty"`
	ExternalPaymentMethods []*PaymentProvider    `json:"external_payment_methods,omitempty"`
	ExternalCheckouts      []*PaymentProvider    `json:"external_checkouts,omitempty"`
	ShippingCountries      []string              `json:"shipping_countries,omitempty"`
	ShippingOptions        []*ShippingOption     `json:"shipping_options,omitempty"`
	MerchantData           string                `json:"merchant_data,omitempty"`
	GUI                    *GUI                  `json:"gui,omitempty"`
	MerchantRequested      *AdditionalCheckBox   `json:"merchant_requested,omitempty"`
	SelectedShippingOption *ShippingOption       `json:"selected_shipping_option,omitempty"`
}

CheckoutOrder type is the request structure to create a new order from the Checkout API

type CheckoutSrv

type CheckoutSrv interface {
	CreateNewOrder(*CheckoutOrder) error
	RetrieveOrder(string) (*CheckoutOrder, error)
	UpdateOrder(string, *CheckoutOrder) error
}

CheckoutSrv type represent the method that the checkout service will expose

func NewCheckoutSrv

func NewCheckoutSrv(c Client) CheckoutSrv

NewCheckoutSrv factory method for the checkoutSrv

type Client

type Client interface {
	Post(path string, body interface{}) (*http.Response, error)
	Patch(path string, body interface{}) (*http.Response, error)
	Get(path string) (*http.Response, error)
	Delete(path string) (*http.Response, error)
}

Client type abstract the functionality that the client should implement, just for more extendability

func NewClient

func NewClient(c Config) Client

NewClient factory method

type Config

type Config struct {
	BaseURL     *url.URL
	APIUsername string
	APIPassword string
	Timeout     time.Duration
}

Config type is the basic configurations required from the client to provide in order to function

type CreateCapture

type CreateCapture struct {
	CapturedAmount int                            `json:"captured_amount"`
	Description    string                         `json:"description,omitempty"`
	OrderLines     []*Line                        `json:"order_lines,omitempty"`
	ShippingInfo   []*OrderManagementShippingInfo `json:"shipping_info,omitempty"`
	ShippingDelay  int                            `json:"shipping_delay,omitempty"`
}

type CustomerAddress

type CustomerAddress struct {
	ShippingAddress *Address `json:"shipping_address,omitempty"`
	BillingAddress  *Address `json:"billing_address,omitempty"`
}

type CustomerInfo

type CustomerInfo struct {
	DateOfBirth string `json:"date_of_birth,omitempty"`
	Gender      string `json:"gender,omitempty"`
	LastFourSSN string `json:"last_four_ssn,omitempty"`
}

CustomerInfo type is Information about the liable customer of the order

type GUI

type GUI struct {
	Options []string `json:"options,omitempty"`
}

GUI type wraps the GUI options

type Line

type Line struct {
	Type                string `json:"type,omitempty"`
	Reference           string `json:"reference,omitempty"`
	Name                string `json:"name"`
	Quantity            int    `json:"quantity"`
	QuantityUnit        string `json:"quantity_unit,omitempty"`
	UnitPrice           int    `json:"unit_price"`
	TaxRate             int    `json:"tax_rate"`
	TotalAmount         int    `json:"total_amount"`
	TotalDiscountAmount int    `json:"total_discount_amount,omitempty"`
	TotalTaxAmount      int    `json:"total_tax_amount"`
	MerchantData        string `json:"merchant_data,omitempty"`
	ProductURL          string `json:"product_url,omitempty"`
	ImageURL            string `json:"image_url,omitempty"`
}

type LineType

type LineType string

LineType The applicable order lines

type MerchantReferences

type MerchantReferences struct {
	MerchantReference1 string `json:"merchant_reference1,omitmepty"`
	MerchantReference2 string `json:"merchant_reference2,omitmepty"`
}

type OrderAmountLines

type OrderAmountLines struct {
	OrderAmount int     `json:"order_amount"`
	Description string  `json:"description,omitempty"`
	OrderLines  []*Line `json:"order_lines,omitempty"`
}

type OrderManagementCustomer

type OrderManagementCustomer struct {
	DateOfBirth                  string `json:"date_of_birth,omitempty"`
	NationalIdentificationNumber string `json:"national_identification_number,omitempty"`
}

type OrderManagementOrder

type OrderManagementOrder struct {
	ID                        string                   `json:"order_id,omitempty"`
	Status                    string                   `json:"status,omitempty"`
	FraudStatus               string                   `json:"fraud_status,omitempty"`
	OrderAmount               int                      `json:"order_amount,omitempty"`
	OriginalOrderAmount       int                      `json:"original_order_amount,omitempty"`
	CapturedAmount            int                      `json:"captured_amount,omitmepty"`
	RefundedAmount            int                      `json:",omitempty"`
	RemainingAuthorizedAmount int                      `json:"remaining_authorized_amount,omitempty"`
	PurchaseCurrency          string                   `json:"purchase_currency,omitempty"`
	Locale                    string                   `json:",omitempty"`
	OrderLines                []*Line                  `json:"order_lines,omitempty"`
	MerchantReference1        string                   `json:"merchant_reference1,omitempty"`
	MerchantReference2        string                   `json:"merchant_reference2,omitempty"`
	KlarnaReference           string                   `json:"klarna_reference"`
	Customer                  *OrderManagementCustomer `json:"customer,omitempty"`
	BillingAddress            *Address                 `json:"billing_address,omitempty"`
	ShippingAddress           *Address                 `json:"shipping_address,omitempty"`
	CreatedAt                 string                   `json:"created_at,omitempty"` // DateTime string of ISO 8601
	PurchaseCountry           string                   `json:"purchase_country,omitempty"`
	ExpiresAt                 string                   `json:"expires_at,omitempty"` // DateTime string of ISO 8601
	Captures                  *[]Capture               `json:"captures,omitempty"`
	Refunds                   *OrderManagementRefund   `json:"refunds,omitempty"`
	MerchantData              string                   `json:"merchant_data,omitempty"`
}

type OrderManagementRefund

type OrderManagementRefund struct {
	RefundAmount int     `json:"refund_amount,omitempty"`
	RefundedAt   string  `json:"refunded_at,omitempty"` // DateTime string of ISO 8601
	Description  string  `json:"description,omitempty"`
	OrderLines   []*Line `json:"order_lines,omitempty"`
}

type OrderManagementShippingInfo

type OrderManagementShippingInfo struct {
	ShippingCompany       string `json:"shipping_company,omitempty"`
	ShippingMethod        string `json:"shipping_method,omitempty"`
	TrackingNumber        string `json:"tracking_number,omitempty"`
	TrackingUri           string `json:"tracking_uri,omitempty"`
	ReturnShippingCompany string `json:"return_shipping_company,omitempty"`
	ReturnTrackingNumber  string `json:"return_tracking_number,omitempty"`
	ReturnTrackingUri     string `json:"return_tracking_uri,omitempty"`
}

type OrderManagementSrv

type OrderManagementSrv interface {
	// Order Management - order end-points
	GetOrder(string) (*OrderManagementOrder, error)
	AcknowledgeOrder(string) error
	SetOrderAmountLines(string, *OrderAmountLines) error
	AdjustOrderAmountLines(string, *AdjustAmountLines) error
	CancelOrder(string) error
	UpdateCustomerAddress(string, *CustomerAddress) error
	ExtendAuthorizationTime(string) error
	UpdateMerchantReferences(string, *MerchantReferences) error
	ReleaseRemainingAuthorization(string) error

	// Order Management - capture end-points
	GetRefund(string, string) error
	CreateRefund(string, *OrderManagementRefund) error
	GetAllCaptures(string) ([]*Capture, error)
	TriggerResendCustomerCommunication(string, string) error
	AddCaptureShippingInfo(string, string, []*OrderManagementShippingInfo) error
	GetCapture(string, string) (*Capture, error)
	CreateCapture(string, *CreateCapture) error
}

func NewOrderManagement

func NewOrderManagement(c Client) OrderManagementSrv

type PaymentMerchantURLS

type PaymentMerchantURLS struct {
	Confirmation string `json:"confirmation"`
	Notification string `json:"notification,omitempty"`
}

The merchant urls structure

type PaymentOptions

type PaymentOptions struct {
	ColorButton            string `json:"color_button,omitempty"`
	ColorButtonText        string `json:"color_button_text,omitempty"`
	ColorCheckbox          string `json:"color_checkbox,omitempty"`
	ColorCheckboxCheckmark string `json:"color_checkbox_checkmark,omitempty"`
	ColorHeader            string `json:"color_header,omitempty"`
	ColorLink              string `json:"color_link,omitempty"`
	ColorBorder            string `json:"color_border,omitempty"`
	ColorBorderSelected    string `json:"color_border_selected,omitempty"`
	ColorText              string `json:"color_text,omitempty"`
	ColorDetails           string `json:"color_details,omitempty"`
	ColorTextSecondary     string `json:"color_text_secondary,omitempty"`
	RadiusBorder           string `json:"radius_border,omitempty"`
}

PaymentOptions type Options for this purchase

type PaymentOrder

type PaymentOrder struct {
	Design             string               `json:"design,omitempty"`
	PurchaseCountry    string               `json:"purchase_country"`
	PurchaseCurrency   string               `json:"purchase_currency"`
	Locale             string               `json:"locale"`
	BillingAddress     *Address             `json:"billing_address"`
	ShippingAddress    *Address             `json:"shipping_address,omitempty"`
	OrderAmount        int                  `json:"order_amount"`
	OrderTaxAmount     int                  `json:"order_tax_amount"`
	OrderLines         []*Line              `json:"order_lines"`
	Customer           *CustomerInfo        `json:"customer,omitempty"`
	MerchantURLS       *PaymentMerchantURLS `json:"merchant_urls,omitempty"`
	MerchantReference1 string               `json:"merchant_reference1,omitempty"`
	MerchantReference2 string               `json:"merchant_reference2,omitempty"`
	Options            *PaymentOptions      `json:"options,omitempty"`
	Attachment         *Attachment          `json:"attachment,omitempty"`
}

PaymentOrder type is the request payload to create an order from the Payment API by providing the order structure and the authorization token

type PaymentOrderInfo

type PaymentOrderInfo struct {
	OrderID     string `json:"order_id,omitempty"`
	RedirectURL string `json:"redirect_url,omitempty"`
	FraudStatus string `json:"fraud_status,omitempty"`
}

PaymentOrderInfo type is the response coming back from creating an order in the Payment API

type PaymentProvider

type PaymentProvider struct {
	Name        string   `json:"name"`
	RedirectURL string   `json:"redirect_url"`
	ImageURL    string   `json:"image_url,omitempty"`
	Fee         int      `json:"fee,omitempty"`
	Description string   `json:"description,omitempty"`
	Countries   []string `json:"countries,omitempty"`
}

PaymentProvider type is part of the CheckoutOrder structure, represent the ExternalPaymentMethods and ExternalCheckouts field

type PaymentSession

type PaymentSession struct {
	// SessionID Id of the created session
	SessionID string `json:"session_id"`
	// ClientToken Token to be passed to the JS client
	ClientToken string `json:"client_token"`
}

SessionResponse type encapsulate the two fields that the API response with when creating a new session

type PaymentSrv

type PaymentSrv interface {
	CreateNewSession(*PaymentOrder) (*PaymentSession, error)
	UpdateExistingSession(string, *PaymentOrder) error
	CreateNewOrder(string, *PaymentOrder) (*PaymentOrderInfo, error)
	CancelExistingAuthorization(string) error
}

PaymentSrv type describe the payment api client methods

func NewPaymentSrv

func NewPaymentSrv(c Client) PaymentSrv

NewPaymentSrv Return a new payment instance while providing

type ShippingOption

type ShippingOption struct {
	ID             string `json:"id"`
	Name           string `json:"name"`
	Description    string `json:"description,omitempty"`
	Promo          string `json:"promo,omitempty"`
	Price          int    `json:"price"`
	TaxAmount      int    `json:"tax_amount"`
	TaxRate        int    `json:"tax_rate"`
	Preselected    bool   `json:"preselected,omitempty"`
	ShippingMethod string `json:"shipping_method,omitempty"`
}

ShippingOption type is part of the CheckoutOrder structure, represent the shipping options field

Jump to

Keyboard shortcuts

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