ChartMogul API GO Client
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
integration_tests
mock_chartmogul
.codeclimate.yml
.test-coverage.sh
.travis.yml
LICENSE
README.md
attributes.go
chartmogul.go
chartmogul_test.go
customers.go
customers_test.go
datasources.go
datasources_test.go
dump-server.js
errors.go
generic.go
generic_test.go
genmocks.sh
invoices.go
invoices_test.go
metrics.go
metrics_activities.go
metrics_subscriptions.go
ping.go
plans.go
subscriptions.go
tags.go
transactions.go

README.md

Official ChartMogul API Go Client

chartmogul-go provides convenient Golang bindings for ChartMogul's API.

Build Status


Installation | Configuration | Usage | Development | Contributing | License



GoDoc Go Report Card

Installation

This library requires Go 1.7.3 or above.

go get github.com/chartmogul/chartmogul-go

Configuration

First create the API struct by passing your account token and secret key, available from the administration section of your ChartMogul account.

import cm "github.com/chartmogul/chartmogul-go"

api := cm.API{
    AccountToken: os.Getenv("CHARTMOGUL_ACCOUNT_TOKEN"),
    AccessKey:    os.Getenv("CHARTMOGUL_SECRET_KEY"),
}

// Try authentication
ok, err := api.Ping()
if err != nil {
    fmt.Printf("This didn't work out: %v", err)
}

This struct has all the methods you can use to interact with ChartMogul.

HTTP 2

ChartMogul's current stable version of nginx is incompatible with HTTP 2 implementation of Go as of 1.7.3. For this reason the application must run with the following (or otherwise prohibit HTTP 2):

export GODEBUG=http2client=0

Usage

Rate Limits

The library retries on HTTP 429 (rate limit reached), so that you don't have to manually handle rate limiting. See: ChartMogul: Rate Limits & BackOff constants. Exponential back-off algorithm is used. It also automatically retries on network errors, eg. when the server can't be reached.

The API calls will retry automatically and block (several minutes), therefore it's still advisable to only use reasonable parallelism. In case it keeps failing after maximum retry period, it will return the HTTP 429 error.

Note: the Ping doesn't retry.

Import API

Available methods in Import API:

Data Sources

api.CreateDataSource("name")
api.ListDataSources()
api.RetrieveDataSource("uuid")
api.DeleteDataSource("uuid")

Customers

api.CreateCustomer(&cm.NewCustomer{})
api.RetrieveCustomer("customerUUID")
api.SearchCustomers(&cm.SearchCustomersParams{})
api.ListCustomers(&cm.ListCustomersParams{})
api.UpdateCustomer(&cm.NewCustomer{}, "customerUUID")
api.MergeCustomers(&cm.MergeCustomersParams{})

Plans

api.CreatePlan(&cm.Plan{Name: "name", ExternalID: "external_id"}, "dataSourceUUID")
api.RetrievePlan("planUUID")
api.ListPlans(&cm.ListPlansParams{Cursor: cm.Cursor{Page: "1", PerPage: "10"}})
api.UpdatePlan(&cm.Plan{}, "planUUID")
api.DeletePlan("planUUID")

Invoices

api.CreateInvoices([]*cm.Invoice{*cm.Invoice{}}, "customerUUID")
api.ListInvoices(&cm.Cursor{}, "customerUUID")
api.ListAllInvoices(&cm.ListAllInvoicesParams{})
api.RetrieveInvoice("invoiceUUID")
api.DeleteInvoice("invoiceUUID")

Transactions

api.CreateTransaction(&cm.Transaction{}, "invoiceUUID")

Subscriptions

api.CancelSubscription("subscriptionUUID", &cm.CancelSubscriptionParams{CancelledAt: "2005-01-01T01:02:03.000Z"})
api.CancelSubscription("subscriptionUUID", &cm.CancelSubscriptionParams{CancellationDates: []string{"2005-01-01T01:02:03.000Z", "2006-10-21T11:21:13.000Z"}})
api.ListSubscriptions(&cm.Cursor{}, "customerUUID")

Customer Attributes

api.RetrieveCustomersAttributes("customerUUID")

Tags

api.AddTagsToCustomer("customerUUID", []string{})
api.AddTagsToCustomersWithEmail("email@customer.com", []string{})

Custom Attributes

api.AddCustomAttributesToCustomer("customerUUID", []*cm.CustomAttribute{})

Metrics API

Available methods in Metrics API:

api.MetricsRetrieveAll(&MetricsFilter{})
api.MetricsRetrieveMRR(&MetricsFilter{})
api.MetricsRetrieveARR(&MetricsFilter{})
api.MetricsRetrieveARPA(&MetricsFilter{})
api.MetricsRetrieveASP(&MetricsFilter{})
api.MetricsRetrieveCustomerCount(&MetricsFilter{})
api.MetricsRetrieveCustomerChurnRate(&MetricsFilter{})
api.MetricsRetrieveMRRChurnRate(&MetricsFilter{})
api.MetricsRetrieveLTV(&MetricsFilter{})

api.MetricsListSubscriptions(&Cursor{}, "customerUUID")
api.MetricsListActivities(&Cursor{}, "customerUUID")

Errors

The library returns parsed errors inside the structs as from the REST API, which is handy eg. when you upload multiple invoices - to know, which one had issues.

type Errors map[string]string

Non-2xx statuses and network problems will also be returned as a value error for standard binary ok/problem handling:

_, err := api.ImportListPlans(nil)
if err != nil {
    // ...
}

Such errors are HTTPError wrapped in errors with stack.

type HTTPError interface {
	StatusCode() int
	Status() string
	Response() string
}
// If you want to check specific HTTP status:
switch e := errors.Cause(err).(type) {
case cm.HTTPError:
    if e.StatusCode() == 422 {
        // special reaction
    }
}

If there are network/TLS issues it will be RequestErrors interface. This has the method Errors() []error.

For fine-grain reaction you can use the parsed errors from API in the primary return structures, when there's an Errors or Error field. You can use hepler methods to spare code on checking map contents:

  • Errors.IsAlreadyExists()
  • Errors.IsInvoiceAndTransactionAlreadyExist()

Development

To work on the library:

  • Fork it
  • Create your feature branch (git checkout -b my-new-feature)
  • Install dependencies: go install
  • Fix bugs or add features. Make sure the changes pass the Go coding standards.
  • Push to the branch (git push origin my-new-feature)
  • Create a new Pull Request

Recommended

  • github.com/davecgh/go-spew/spew for debugging data (reference documentation output done using this library).
  • add pre-commit hook go test ./... (in .git/hooks/pre-commit) to have a working state always.

Testing

  • Use net/http/httptest for mocking HTTP server directly, see file generic_test.go for examples.
  • For integration_tests against real API use github.com/dnaeon/go-vcr library. Be careful to remove your API credentials from fixtures before committing! If Import API App changes, re-record the affected integration tests (by deleting fixtures).

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/chartmogul/chartmogul-go.

License

The library is available as open source under the terms of the MIT License.

The MIT License (MIT)

Copyright (c) 2017 ChartMogul Ltd.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.