Skip to content

Latest commit

 

History

556 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Go Client Library for GoCardless API

This library provides a simple wrapper around the GoCardless API.

Getting started

Make sure your project is using Go Modules (it will have a go.mod file in its root if it already is):

go mod init
go mod tidy

Then, reference gocardless-pro-go in a Go program with import:

import (
    gocardless "github.com/gocardless/gocardless-pro-go/v6"
)

Run any of the normal go commands (build/install/test). The Go toolchain will resolve and fetch the gocardless-pro-go module automatically.

Alternatively, you can also explicitly go get the package into a project:

go get -u github.com/gocardless/gocardless-pro-go@v6.7.0

Initializing the client

The client is initialised with an access token, and is configured to use GoCardless live environment by default:

    token := "your_access_token"
    config, err := gocardless.NewConfig(token)
    if err != nil {
        fmt.Printf("got err in initialising config: %s", err.Error())
        return
    }
    client, err := gocardless.New(config)
    if err != nil {
		fmt.Printf("error in initialisating client: %s", err.Error())
		return
	}

Optionally, the client can be customised with endpoint, for ex: sandbox environment

    config, err := gocardless.NewConfig(token, gocardless.WithEndpoint(gocardless.SandboxEndpoint))
    if err != nil {
        fmt.Printf("got err in initialising config: %s", err.Error())
        return
    }
    client, err := gocardless.New(config)
    if err != nil {
		fmt.Printf("error in initialisating client: %s", err.Error())
		return
	}

the client can also be initialised with a customised http client, for ex;

    customHttpClient := &http.Client{
        Timeout: time.Second * 10,
    }
    config, err := gocardless.NewConfig(token, gocardless.WithClient(customHttpClient))
    if err != nil {
        fmt.Printf("got err in initialising config: %s", err.Error())
        return
    }
    client, err := gocardless.New(config)
    if err != nil {
		fmt.Printf("error in initialisating client: %s", err.Error())
		return
	}

Examples

Fetching resources

To fetch single item, use the Get method

    ctx := context.TODO()
    customer, err := client.Customers.Get(ctx, "CU123")

Listing resources

To fetch items in a collection, there are two options:

  • Fetching items one page at a time using List method:
    ctx := context.TODO()
    customerListParams := gocardless.CustomerListParams{}
    customers, err := client.Customers.List(ctx, customerListParams)
    for _, customer := range customers.Customers {
        fmt.Printf("customer: %v", customer)
    }
    cursor := customers.Meta.Cursors.After
    customerListParams.After = cursor
    nextPageCustomers, err := client.Customers.List(ctx, customerRemoveParams)
  • Iterating through all of the items using a All method to get a lazily paginated list. All will deal with making extra API requests to paginate through all the data for you:
    ctx := context.TODO()
    customerListParams := gocardless.CustomerListParams{}
    customerListIterator := client.Customers.All(ctx, customerListParams)
    for customerListIterator.Next() {
        customerListResult, err := customerListIterator.Value(ctx)
        if err != nil {
            fmt.Printf("got err: %s", err.Error())
        } else {
            fmt.Printf("customerListResult is %v", customerListResult)
        }
    }

Creating resources

Resources can be created with the Create method:

    ctx := context.TODO()
    customerCreateParams := gocardless.CustomerCreateParams{
        AddressLine1: "9 Acer Gardens"
        City:         "Birmingham",
        PostalCode:   "B4 7NJ",
        CountryCode:  "GB",
        Email:        "bbr@example.com",
        GivenName:    "Bender Bending",
        FamilyName:   "Rodgriguez",
    }

    customer, err := client.Customers.Create(ctx, customerCreateParams)

Updating Resources

Resources can be updates with the Update method:

    ctx := context.TODO()
    customerUpdateParams := CustomerUpdateParams{
        GivenName: "New Name",
    }

    customer, err := client.Customers.Update(ctx, "CU123", customerUpdateParams)

Removing Resources

Resources can be removed with the Remove method:

    ctx := context.TODO()
    customerRemoveParams := CustomerRemoveParams{}

    customer, err := client.Customers.Remove(ctx, "CU123", customerRemoveParams)

Retrying requests

The library will attempt to retry most failing requests automatically (with the exception of those which are not safe to retry).

GET requests are considered safe to retry, and will be retried automatically. Certain POST requests are made safe to retry by the use of an idempotency key, generated automatically by the library, so we'll automatically retry these too. Currently its retried for 3 times. If you want to override this behaviour(for example, to provide your own retry mechanism), then you can use the WithoutRetries. This will not retry and return response object.

    requestOption := gocardless.WithoutRetries()
    customersCreateResult, err := client.Customers.Create(ctx, customerCreateParams, requestOption)

Setting custom headers

You shouldn't generally need to customise the headers sent by the library, but you wish to in some cases (for example if you want to send an Accept-Language header when creating a mandate PDF).

    headers := make(map[string]string)
    headers["Accept-Language"] = "fr"
    requestOption := gocardless.WithHeaders(headers)
    customersCreateResult, err := client.Customers.Create(ctx, customerCreateParams, requestOption)

Custom headers you specify will override any headers generated by the library itself (for example, an Idempotency-Key header with a randomly-generated value or one you've configured manually). Custom headers always take precedence.

    requestOption := gocardless.WithIdempotencyKey("test-idemptency-key-123")
    customersCreateResult, err := client.Customers.Create(ctx, customerCreateParams, requestOption)

Handling webhooks

GoCardless supports webhooks, allowing you to receive real-time notifications when things happen in your account, so you can take automatic actions in response, for example:

  • When a customer cancels their mandate with the bank, suspend their club membership
  • When a payment fails due to lack of funds, mark their invoice as unpaid
  • When a customer’s subscription generates a new payment, log it in their “past payments” list

The client allows you to validate that a webhook you receive is genuinely from GoCardless, and to parse it into Event objects(defined in event_service.go) which are easy to work with:

    http.HandleFunc("/webhookEndpoint", func(w http.ResponseWriter, r *http.Request) {
        wh, err := NewWebhookHandler("secret", EventHandlerFunc(func(event gocardless.Event) error {
		    parseEvent(event)
        }))
        wh.ServeHTTP(w,r)
    })

    func parseEvents(event Event) {
        // work through list of events
    }

Accessing the webhook ID

If you need to access the webhook ID for debugging purposes, you can use ParseWebhook to get both the events and webhook metadata:

    result, err := gocardless.ParseWebhook(requestBody, signatureHeader, webhookEndpointSecret)
    if err != nil {
        // Handle invalid signature error
    }
    events := result.Events
    webhookId := result.WebhookId  // e.g. "WB123" - useful for debugging

Note: The webhook ID is intended for debugging and logging purposes only. It should not be used for deduplication - instead, use the event IDs to deduplicate, as each event has a unique ID that remains consistent if the same event is sent multiple times.

Error Handling

When the library returns an error defined by us rather than the stdlib, it can be converted into a gocardless.APIError using errors.As:

    billingRequest, err := client.BillingRequests.Create(ctx, billingRequestCreateParams)
	if err != nil {
		var apiErr *gocardless.APIError
		if errors.As(err, &apiErr) {
			fmt.Printf("got err: %v", apiErr.Message)
		}
		return nil, err
	}

Compatibility

This library requires go 1.20 and above.

Upgrading from older versions

If you're upgrading from v5 or earlier to v6 or later, see: MIGRATION_V6.md

Contributing

This client is auto-generated from Crank, a toolchain that we hope to soon open source. Issues should for now be reported on this repository. Please do not modify the source code yourself, your changes will be overridden!

About

GoCardless Go Client

Resources

Security policy

Stars

12 stars

Watchers

43 watching

Forks

Releases

Packages

Used by

Contributors

Languages