gocardless

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

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

Go to latest
Published: Jul 28, 2018 License: MIT Imports: 11 Imported by: 0

README

Go client for Gocardless Pro API

Godoc Build Status Go Report Card

This package allows integrating your Golang application with Gocardless Pro

Installation

Standard go get:

go get github.com/epigos/gocardless-go

Coverage

  • Customers
  • Customer Bank Accounts
  • Mandates
  • Payments

Usage

Create a Client instance, providing your access token and the environment you want to use:

package main

import (
    "fmt"
    "os"
    gocardless "github.com/epigos/gocardless-go"
)

func main() {
    token := os.Getenv("GOCARDLESS_ACCESS_TOKEN")
    client := gocardless.NewClient(token, gocardless.SandboxEnvironment)
    
    // get customers
    res, err := client.GetCustomers()
    for _, c := range res.Customers {
        fmt.Println(c)
    }
}

Documentation

Documentation

Overview

Package gocardless is a Go client for interacting with the GoCardless Pro API.

Example:

Create a Client instance, providing your access token and the environment you want to use:

package main

import (
  "fmt"
  "os"
  gocardless "github.com/epigos/gocardless-go"
)

func main() {
  // gocardless access token
  token := os.Getenv("GOCARDLESS_ACCESS_TOKEN")

  // gocardless client using Sandbox environment
  client := gocardless.NewClient(token, gocardless.SandboxEnvironment)

  // get customers
  res, err := client.GetCustomers()

  if err != nil {
    fmt.Println(err)
  }
  fmt.Println(res)
}

Learn more about GoCardless Pro API https://developer.gocardless.com/

Index

Examples

Constants

View Source
const (
	// InvalidMethodError details when a request is passed, but the method is invalid in the current context
	InvalidMethodError = `The request Method is invalid`
)

Variables

This section is empty.

Functions

func Centify

func Centify(amount float64) int

Centify amount in floats by multiplying by 100, so 12.25 -> 1225. Use when creating payments as amount should be in Pence or Cents

Types

type Client

type Client struct {
	// AccessToken is the bearer token used to authenticate requests to the GoCardless API
	AccessToken string
	// RemoteURL is the address of the GoCardless API
	RemoteURL string
}

Client for interacting with the GoCardless Pro API

func NewClient

func NewClient(accessToken string, env Environment) *Client

NewClient instantiate a client struct with your access token and environment, then use the resource methods to access the API

func (*Client) CancelMandate

func (c *Client) CancelMandate(id string) (*Mandate, error)

CancelMandate immediately cancels a mandate and all associated cancellable payments.

Relative endpoint: POST /mandates/MD123/actions/cancel

func (*Client) CancelPayment

func (c *Client) CancelPayment(payment *Payment) error

CancelPayment immediately cancels a payment and all associated cancellable payments.

Relative endpoint: POST /payments/PM123/actions/cancel

func (*Client) CreateCustomer

func (c *Client) CreateCustomer(customer *Customer) error

CreateCustomer creates a new customer object

Relative endpoint: POST /customers

func (*Client) CreateCustomerBankAccount

func (c *Client) CreateCustomerBankAccount(cba *CustomerBankAccount) error

CreateCustomerBankAccount creates a new customer bank account object.

Relative endpoint: POST /customer_bank_accounts

func (*Client) CreateMandate

func (c *Client) CreateMandate(mandate *Mandate) error

CreateMandate creates a new mandate object.

Relative endpoint: POST /mandates

func (*Client) CreatePayment

func (c *Client) CreatePayment(payment *Payment) error

CreatePayment creates a new payment object.

Relative endpoint: POST /payments

func (*Client) DisableCustomerBankAccount

func (c *Client) DisableCustomerBankAccount(id string) (*CustomerBankAccount, error)

DisableCustomerBankAccount disables a bank account and immediately cancels all associated mandates and cancellable payments

Relative endpoint: POST /customer_bank_accounts/BA123/actions/disable

func (*Client) GetCustomer

func (c *Client) GetCustomer(id string) (*Customer, error)

GetCustomer retrieves the details of an existing customer.

Relative endpoint: GET /customers/CU123

func (*Client) GetCustomerBankAccount

func (c *Client) GetCustomerBankAccount(id string) (*CustomerBankAccount, error)

GetCustomerBankAccount Retrieves the details of an existing bank account.

Relative endpoint: GET /customer_bank_accounts/BA123

func (*Client) GetCustomerBankAccounts

func (c *Client) GetCustomerBankAccounts() (*CustomerBankAccountListResponse, error)

GetCustomerBankAccounts returns a cursor-paginated list of your bank accounts.

Relative endpoint: GET /customer_bank_accounts

func (*Client) GetCustomers

func (c *Client) GetCustomers() (*CustomerListResponse, error)

GetCustomers returns a cursor-paginated list of your customers.

Relative endpoint: GET /customers

func (*Client) GetMandate

func (c *Client) GetMandate(id string) (*Mandate, error)

GetMandate retrieves the details of an existing mandate.

Relative endpoint: GET /mandates/MD123

func (*Client) GetMandates

func (c *Client) GetMandates() (*MandateListResponse, error)

GetMandates returns a cursor-paginated list of your mandates.

Relative endpoint: GET /mandates

func (*Client) GetPayment

func (c *Client) GetPayment(id string) (*Payment, error)

GetPayment retrieves the details of an existing payment.

Relative endpoint: GET /payments/PM123

func (*Client) GetPayments

func (c *Client) GetPayments() (*PaymentListResponse, error)

GetPayments returns a cursor-paginated list of your payments.

Relative endpoint: GET /payments

func (*Client) ReinstateMandate

func (c *Client) ReinstateMandate(id string) (*Mandate, error)

ReinstateMandate Reinstates a cancelled or expired mandate to the banks.

Relative endpoint: POST /mandates/MD123/actions/reinstate

func (*Client) RetryPayment

func (c *Client) RetryPayment(payment *Payment) error

RetryPayment Retries a failed payment if the underlying mandate is active.

Relative endpoint: POST /payments/PM123/actions/retry

func (*Client) UpdateCustomer

func (c *Client) UpdateCustomer(customer *Customer) error

UpdateCustomer Updates a customer object. Supports all of the fields supported when creating a customer.

Relative endpoint: PUT /customers/CU123

func (*Client) UpdateCustomerBankAccount

func (c *Client) UpdateCustomerBankAccount(cba *CustomerBankAccount) error

UpdateCustomerBankAccount Updates a customer bank account object. Only the metadata parameter is allowed.

Relative endpoint: PUT /customer_bank_accounts/BA123

func (*Client) UpdateMandate

func (c *Client) UpdateMandate(mandate *Mandate) error

UpdateMandate Updates a mandate object. Supports all of the fields supported when creating a mandate.

Relative endpoint: PUT /mandates/MD123

func (*Client) UpdatePayment

func (c *Client) UpdatePayment(payment *Payment) error

UpdatePayment Updates a payment object. Supports all of the fields supported when creating a payment.

Relative endpoint: PUT /payments/PM123

type Cursor

type Cursor struct {
	// Before ID of the object immediately following the array of objects to be returned
	Before string `json:"before"`
	// After ID of the object immediately preceding the array of objects to be returned
	After string `json:"after"`
}

Cursor pagination parameters

type Customer

type Customer struct {
	// ID is a unique identifier, beginning with “CU”.
	ID string `json:"id,omitempty"`
	// AddressLine1 is the first line of the customer’s address.
	AddressLine1 string `json:"address_line1"`
	// AddressLine2 is the first line of the customer’s address.
	AddressLine2 string `json:"address_line2"`
	// AddressLine3 is the first line of the customer’s address.
	AddressLint3 string `json:"address_line3"`
	// City is the city of the customer’s address.
	City string `json:"city"`
	// CompanyName is the customer’s company name. Required unless a given_name and family_name are provided.
	CompanyName string `json:"company_name"`
	// CountryCode is the ISO 3166-1 alpha-2 code.
	CountryCode string `json:"country_code"`
	// CreatedAt is a fixed timestamp, recording when the customer was created.
	CreatedAt *time.Time `json:"created_at,omitempty"`
	// Email is the customer's email address
	Email string `json:"email,omitempty"`
	// FamilyName is the customer's surname. Required unless a CompanyName is provided
	FamilyName string `json:"family_name"`
	// GivenName is the customer's first name. Required unless a CompanyName is provided
	GivenName string `json:"given_name"`
	// Language is a ISO 639-1 code. Used as the language for notification emails sent by GoCardless if your
	// organisation does not send its own (see compliance requirements). Currently only “en”, “fr”, “de”, “pt”,
	// “es”, “it”, “nl”, “sv” are supported. If this is not provided, the language will be chosen based on the
	// country_code (if supplied) or default to “en”.
	Language string `json:"language,omitempty"`
	// Metadata is a key-value store of custom data. Up to 3 keys are permitted, with key names up to 50
	// characters and values up to 500 characters.
	Metadata map[string]string `json:"metadata,omitempty"`
	// PostalCode is the customers postal code
	PostalCode string `json:"postal_code"`
	// Region is the customer's address region, county or department
	Region string `json:"region"`
	// SwedishIdentityNumber is for Swedish customers only. The civic/company number (personnummer,
	// samordningsnummer, or organisationsnummer) of the customer. Must be supplied if the customer’s bank
	// account is denominated in Swedish krona (SEK). This field cannot be changed once it has been set.
	SwedishIdentityNumber string `json:"swedish_identity_number,omitempty"`
}

Customer struct hold the contact details for a customer

Example
// Create a Client instance, providing your access token and the environment you want to use
token := os.Getenv("GOCARDLESS_ACCESS_TOKEN")
client := NewClient(token, SandboxEnvironment)

// create customer
cm := NewCustomer("user@example.com", "Frank", "Osborne", "27 Acer Road", "Apt 2", "London", "E8 3GX", "GB")
cm.AddMetadata("salesforce_id", "ABCD1234")
err := client.CreateCustomer(cm)

if err != nil {
	panic(err)
}
fmt.Println(cm)

// retrieve customer
cm, err = client.GetCustomer(cm.ID)
if err != nil {
	panic(err)
}
fmt.Println(cm)
// get customers
res, err := client.GetCustomers()
if err != nil {
	panic(err)
}
fmt.Println(res)

// update customer
cm.CompanyName = "Google.com"
err = client.UpdateCustomer(cm)
if err != nil {
	panic(err)
}
fmt.Println(cm)
Output:

func NewCustomer

func NewCustomer(email, givenName, familyName, line1, line2, city, postalCode, countryCode string) *Customer

NewCustomer instantiate a new customer object

func (*Customer) AddMetadata

func (cm *Customer) AddMetadata(key, value string)

AddMetadata adds new metadata item to customer object

func (*Customer) String

func (cm *Customer) String() string

type CustomerBankAccount

type CustomerBankAccount struct {
	// ID is a unique identifier, beginning with "BA".
	ID string `json:"id,omitempty"`
	// AccountHolderName Name of the account holder, as known by the bank.
	// Usually this matches the name of the linked customer.
	// This field will be transliterated, upcased and truncated to 18 characters.
	AccountHolderName string `json:"account_holder_name"`
	// AccountNumber Bank account number. Alternatively you can provide an iban
	AccountNumber string `json:"account_number"`
	// BankCode Bank code
	BankCode string `json:"bank_code,omitempty"`
	// BankCode Bank code
	BranchCode string `json:"branch_code"`
	// AccountNumberEnding Last two digits of account number
	AccountNumberEnding string `json:"account_number_ending,omitempty"`
	// BankName Name of bank, taken from the bank details
	BankName string `json:"bank_name,omitempty"`
	// CountryCode is the ISO 3166-1 alpha-2 code.
	CountryCode string `json:"country_code"`
	// Currency currency code, defaults to national currency of country_code
	Currency string `json:"currency,omitempty"`
	// IBAN International Bank Account Number
	IBAN string `json:"iban,omitempty"`
	// Metadata is a key-value store of custom data. Up to 3 keys are permitted, with key names up to 50
	// characters and values up to 500 characters.
	Metadata map[string]string `json:"metadata,omitempty"`
	// Links links constains customers id
	Links customerLinks `json:"links"`
	// Enabled indicates if bank account is disabled
	Enabled bool `json:"enabled,omitempty"`
}

CustomerBankAccount Customer Bank Accounts hold the bank details of a customer. They always belong to a customer, and may be linked to several Direct Debit mandates.

func NewCustomerBankAccount

func NewCustomerBankAccount(accountNumber, accountName, branchCode, countryCode, customerID string) *CustomerBankAccount

NewCustomerBankAccount instantiate a new customer bank account object

func (*CustomerBankAccount) AddMetadata

func (ca *CustomerBankAccount) AddMetadata(key, value string)

AddMetadata adds new metadata item to customer object

func (*CustomerBankAccount) String

func (ca *CustomerBankAccount) String() string

type CustomerBankAccountListResponse

type CustomerBankAccountListResponse struct {
	CustomerBankAccounts []*CustomerBankAccount `json:"customer_bank_accounts"`
	Meta                 Meta                   `json:"meta,omitempty"`
}

CustomerBankAccountListResponse a List response of CustomerBankAccount instances

type CustomerListResponse

type CustomerListResponse struct {
	Customers []*Customer `json:"customers"`
	Meta      Meta        `json:"meta,omitempty"`
}

CustomerListResponse a List response of Customer instances

type Date

type Date struct {
	time.Time
}

Date an alias of time.Time for parsing json dates in the response

func (*Date) UnmarshalJSON

func (d *Date) UnmarshalJSON(b []byte) error

UnmarshalJSON imeplement Marshaler und Unmarshalere interface

type Environment

type Environment string

Environment represents the environment that the Client will connect to

const (
	// SandboxEnvironment is the name of the sandbox environment in the GoCardless API
	SandboxEnvironment Environment = "sandbox"

	// LiveEnvironment is the name of the live environment in the GoCardless API
	//
	// The following restrictions exist in live.
	//
	// CREDITOR MANAGEMENT RESTRICTIONS
	//
	// Unless your account has previously been approved as a whitelabel partner you may only collect payments on behalf
	// of a single creditor. The following endpoints are therefore restricted:
	//
	// Creditors: Create
	LiveEnvironment Environment = "live"
)

type Error

type Error struct {
	DocumentationURL string         `json:"documentation_url"`
	Message          string         `json:"message"`
	RequestID        string         `json:"request_id"`
	Details          []*ErrorDetail `json:"errors"`
	Type             string         `json:"type"`
	Code             int            `json:"code"`
}

Error base exception class for GoCardless API errors. API errors will result in of this

func (Error) Error

func (err Error) Error() string

type ErrorDetail

type ErrorDetail struct {
	Message        string `json:"message"`
	Field          string `json:"field"`
	RequestPointer string `json:"request_pointer"`
}

ErrorDetail a struct containing the reason for the errors

type InvalidEnvironment

type InvalidEnvironment error

InvalidEnvironment invalid environment exception

type Mandate

type Mandate struct {
	// ID is a unique identifier, beginning with “MD”.
	ID string `json:"id,omitempty"`
	// CreatedAt is a fixed timestamp, recording when the mandate was created.
	CreatedAt *time.Time `json:"created_at,omitempty"`
	// Metadata is a key-value store of custom data. Up to 3 keys are permitted, with key names up to 50
	// characters and values up to 500 characters.
	Metadata map[string]string `json:"metadata,omitempty"`
	// NextPossibleChargeDate The earliest date a newly created payment for this mandate could be charged
	NextPossibleChargeDate *Date `json:"next_possible_charge_date,omitempty"`
	// PaymentRequireApproval Boolean value showing whether payments and
	// subscriptions under this mandate require approval via an automated email before being processed
	PaymentRequireApproval bool `json:"payments_require_approval,omitempty"`
	// Reference Unique reference
	// Different schemes have different length and character set requirements
	// GoCardless will generate a unique reference satisfying the different scheme requirements if this field is left blank
	Reference string `json:"reference,omitempty"`
	// Scheme Direct Debit scheme to which this mandate and associated payments are submitted
	Scheme string `json:"scheme,omitempty"`
	// Status status of mandate.
	Status string `json:"status,omitempty"`
	// Links links to cusomer and bank accounts
	Links mandateLinks `json:"links"`
}

Mandate Mandates represent the Direct Debit mandate with a customer.

func NewMandate

func NewMandate(bankAccountID string) *Mandate

NewMandate instantiate new mandate object

func (*Mandate) AddMetadata

func (m *Mandate) AddMetadata(key, value string)

AddMetadata adds new metadata item to mandate object

func (*Mandate) String

func (m *Mandate) String() string

type MandateListResponse

type MandateListResponse struct {
	Mandates []*Mandate `json:"mandates"`
	Meta     Meta       `json:"meta,omitempty"`
}

MandateListResponse a List response of Mandate instances

type Meta

type Meta struct {
	Cursors Cursor `json:"cursors"`
	// Limit Upper bound for the number of objects to be returned. Defaults to 50. Maximum of 500
	Limit int `json:"limit"`
}

Meta contains pagination cursor for list endpoints

func (Meta) String

func (m Meta) String() string

type Payment

type Payment struct {
	// ID is a unique identifier, beginning with "PM".
	ID string `json:"id,omitempty"`
	// Amount in pence (GBP), cents (AUD/EUR), öre (SEK), or øre (DKK).
	// e.g 1000 is 10 GBP in pence
	Amount int `json:"amount"`
	// AmountRefunded is amount refunded in pence/cents/öre/øre.
	AmountRefunded int `json:"amount_refunded,omitempty"`
	// ChargeDate A future date on which the payment should be collected.
	// If not specified, the payment will be collected as soon as possible
	ChargeDate *Date `json:"charge_date,omitempty"`
	// CreatedAt is a fixed timestamp, recording when the payment was created.
	CreatedAt *time.Time `json:"created_at,omitempty"`
	// Currency currency code, defaults to national currency of country_code
	Currency string `json:"currency"`
	// Description A human-readable description of the payment
	Description string `json:"description,omitempty"`
	// Metadata is a key-value store of custom data. Up to 3 keys are permitted, with key names up to 50
	// characters and values up to 500 characters.
	Metadata map[string]string `json:"metadata,omitempty"`
	// Reference An optional payment reference that will appear on your customer’s bank statement
	Reference string `json:"reference,omitempty"`
	// Status status of payment.
	Status string `json:"status,omitempty"`
	// Links to cusomer and payment
	Links paymentLinks `json:"links"`
	// AppFee The amount to be deducted from the payment as the OAuth app’s fee, in pence/cents/öre/øre
	AppFee int `json:"app_fee,omitempty"`
}

Payment objects represent payments from a customer to a creditor, taken against a Direct Debit payment.

func NewPayment

func NewPayment(amount int, currency, mandateID string) *Payment

NewPayment instantiate new payment object

func (*Payment) AddMetadata

func (p *Payment) AddMetadata(key, value string)

AddMetadata adds new metadata item to payment object

func (*Payment) String

func (p *Payment) String() string

type PaymentListResponse

type PaymentListResponse struct {
	Payments []*Payment `json:"payments"`
	Meta     Meta       `json:"meta,omitempty"`
}

PaymentListResponse a List response of Payment instances

type RateLimitedExceededError

type RateLimitedExceededError struct {
}

RateLimitedExceededError rate limit error

func (*RateLimitedExceededError) Error

func (err *RateLimitedExceededError) Error() string

type Response

type Response struct {
	*http.Response
}

Response response from the API request, providing access to the status code, headers, and body

func (*Response) RateLimit

func (resp *Response) RateLimit() int

RateLimit the rate limit for each request currently, this limit stands at 1000 requests per minute

func (*Response) RateLimitRemaining

func (resp *Response) RateLimitRemaining() int

RateLimitRemaining indicate how many requests are allowed in the current time window

func (*Response) RateReset

func (resp *Response) RateReset() time.Time

RateReset indicates the time after which the rate limit will reset

Jump to

Keyboard shortcuts

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