Giter Club home page Giter Club logo

coinbase-commerce-go's Introduction

Coinbase Commerce Go

The unofficial Go library for the Coinbase Commerce API.

Table of contents

Documentation

For more details visit Coinbase API docs.

To start using this library register an account on Coinbase Commerce. You will find your API_KEY from User Settings.

Next initialize a HttpCoinbaseClient for interacting with the API. The only required parameter to initialize a client is API_KEY

Default timeout for the http client is 3 seconds*, you can change that value like so:

import "github.com/opaolini/coinbase-commerce-go"

func main() {
    c := coinbase.NewHttpClient("API_KEY").WithClientTimeout(3000) // Optional timeout specification in milliseconds
}

Error handling

Client supports the handling of common API errors and warnings.

Error Status Code
APIError *
InvalidRequestError 400
ParamRequiredError 400
ValidationError 400
AuthenticationError 401
ResourceNotFoundError 404
RateLimitExceededError 429
InternalServerError 500
ServiceUnavailableError 503

Example of handling errors from the API:

checkoutID := "random-id"
result, err := c.RetrieveCheckout(checkoutID)
if err != nil {
    switch err.(type) {
    case ResponseError:
        responseError, _ := err.(ResponseError)
        if responseError.IsValidationError() {
            log.Printf("Provided checkout ID: %s is invalid: %s \n", checkoutID, responseError.ReturnedError.Message)
        }
    }
}

Installation

Install with go:

go get github.com/opaolini/coinbase-commerce-go

Usage

import "github.com/opaolini/coinbase-commerce-go"

func main() {
    c := coinbase.NewHttpClient("API_KEY")
}

Checkouts

Checkouts API docs

Retrieve

checkout, err := c.RetrieveCheckout(<checkout_id>)
if err != nil {
   panic(err)
}

Create

checkoutData := Checkout{
    Name:        "The Sovereign Individual",
    Description: "Mastering the Transition to the Information Age",
    PricingType: FixedPrice,
    LocalPrice: LocalPrice{
        Amount:   "100.00",
        Currency: "USD",
    },
    RequestedInfo: []string{"name", "email"},
}

checkout, err := c.CreateCheckout(checkoutData)
if err != nil {
    panic(err)
}

fmt.Println(checkout)

Update

checkoutData := Checkout{
    Name:        "The Sovereign Individual",
    Description: "Mastering the Transition to the Information Age",
    PricingType: FixedPrice,
    LocalPrice: LocalPrice{
        Amount:   "100.00",
        Currency: "USD",
    },
    RequestedInfo: []string{"name", "email"},
}

checkout, err := c.CreateCheckout(checkoutData)
if err != nil {
    panic(err)
}

checkout.LocalPrice = LocalPrice{
    Amount:   "200",
    Currency: "USD",
}

updatedCheckout, err := c.UpdateCheckout(checkout)
if err != nil {
    panic(err)
}

fmt.Println(updatedCheckout)

Delete

checkoutData := Checkout{
    Name:        "The Sovereign Individual",
    Description: "Mastering the Transition to the Information Age",
    PricingType: FixedPrice,
    LocalPrice: LocalPrice{
        Amount:   "100.00",
        Currency: "USD",
    },
    RequestedInfo: []string{"name", "email"},
}

checkout, err := c.CreateCheckout(checkoutData)
if err != nil {
    panic(err)
}

err = c.DeleteCheckout(checkout.ID)

if err != nil {
    panic(err)
}

List

checkouts, err := c.ListCheckouts(nil) // grabs all
if err != nil {
    panic("unexpected error: ", err)
}

fmt.Println(len(checkouts))

With Pagination

p := &Pagination{
		Limit: 50,
	}
checkouts, err := c.ListCheckouts(p) 
if err != nil {
    panic("unexpected error: ", err)
}

fmt.Println(len(checkouts))

Charges

Charges API docs

Retrieve

charge, err := c.RetrieveCharge("76936406-dac7-45f9-8efd-b7a5f8efa7ee")
if err == nil {
    panic("we should not end up here")
}
fmt.Println(charge)

Create

chargeRequest := ChargeRequest{
    Name:        "The Sovereign Individual",
    Description: "Mastering the Transition to the Information Age",
    PricingType: FixedPrice,
    LocalPrice: LocalPrice{
        Amount:   "100.00",
        Currency: "USD",
    },
}

charge, err := c.CreateCharge(chargeRequest)
if err != nil {
    panic(err)
}
fmt.Println(charge)

List

charges, err := c.ListCharges(nil)
if err != nil {
    panic(err)
}

fmt.Println(len(charges))

With pagination

p := &Pagination{
		Limit: 50,
	}
charges, err := c.ListCharges(p)
if err != nil {
    panic(err)
}

fmt.Println(len(charges))

Webhooks

Verify Signature from http.Request

func HandleWebhook(w http.ResponseWriter, r *http.Request) {
	sharedKey := "your-shared-key"
	ok, err := VerifyWebhookSignatureFromRequest(sharedKey, r)
	if err != nil {
		// handle error
		panic(err)
	}

	if !ok {
		// handle invalid signature
	}
}

Verify Signature

    sharedKey := "your-shared-key"
    signature := ""
    body := []byte("{}")
    ok, err := VerifyWebhookSignature(sharedKey, signature, body)
	if err != nil {
		// handle error
		panic(err)
	}

	if !ok {
		// handle invalid signature
	}

TODOs

  • Add some mock tests, as coinbase-commerce does not currently have a sandbox
  • Handle pagination properly
  • Add Webhook signature verification

License

MIT

coinbase-commerce-go's People

Contributors

majortotem avatar opaolini avatar

Watchers

 avatar  avatar

coinbase-commerce-go's Issues

Unoptimal example of error handling

Hello, in README you provide an example of error handling, but the code can be written in more efficient way:

Instead this

if err != nil {
    switch err.(type) {
    case ResponseError:
        responseError, _ := err.(ResponseError)
        if responseError.IsValidationError() {
            log.Printf("Provided checkout ID: %s is invalid: %s \n", checkoutID, responseError.ReturnedError.Message)
        }
    }
}

You can use that

if err != nil {
    switch respErr := err.(type) {
    case ResponseError:
        if respErr.IsValidationError() {
            log.Printf("Provided checkout ID: %s is invalid: %s \n", checkoutID, respErr.ReturnedError.Message)
        }
    }
}

I hope that makes sense for newcomers ๐Ÿ‘

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.