chartmogul

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2019 License: MIT Imports: 9 Imported by: 0

README

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{})
api.ConnectSubscriptions("customerUUID", []cm.Subscription{})
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
  • 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.

Documentation

Overview

Package chartmogul is a simple Go API library for Chartmogul public API.

HTTP 2

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

export GODEBUG=http2client=0

Uses the library gorequest, which allows simple struct->query, body->struct, struct->body.

Index

Constants

View Source
const (

	// AttrTypeString is one of the possible data types for custom attributes.
	AttrTypeString = "String"
	// AttrTypeInteger is one of the possible data types for custom attributes.
	AttrTypeInteger = "Integer"
	// AttrTypeTimestamp is one of the possible data types for custom attributes.
	AttrTypeTimestamp = "Timestamp"
	// AttrTypeBoolean is one of the possible data types for custom attributes.
	AttrTypeBoolean = "Boolean"
)
View Source
const (

	// ErrKeyExternalID is key in Errors map indicating there's a problem with External ID of the resource.
	ErrKeyExternalID = "external_id"
	// ErrKeyTransactionExternalID is key in Errors map indicating there's a problem with External ID of the transaction.
	ErrKeyTransactionExternalID = "transactions.external_id"
	// ErrKeyName - data source name
	ErrKeyName = "name"
	// ErrValCustomerExternalIDExists = can't import new customer with the same external ID
	ErrValCustomerExternalIDExists = "The external ID for this customer already exists in our system."
	// ErrValExternalIDExists = can't save Transaction, because it exists already.
	ErrValExternalIDExists = "has already been taken"
	// ErrValInvoiceExternalIDExists = invoice already exists
	ErrValInvoiceExternalIDExists = "The external ID for this invoice already exists in our system."
	// ErrValPlanExternalIDExists = plan already exists
	ErrValPlanExternalIDExists = "A plan with this identifier already exists in our system."
	// ErrValHasAlreadyBeenTaken = data source name taken
	ErrValHasAlreadyBeenTaken = "Has already been taken."
)

Variables

This section is empty.

Functions

func SetURL

func SetURL(specialURL string)

SetURL changes target URL for the module globally.

func Setup

func Setup(timeoutConf time.Duration)

Setup configures global timeout for the library.

Types

type API

type API struct {
	AccountToken string
	AccessKey    string
	Client       *http.Client
}

API is the handle for communicating with Chartmogul.

func (API) AddCustomAttributesToCustomer

func (api API) AddCustomAttributesToCustomer(customerUUID string, customAttributes []*CustomAttribute) (*CustomAttributes, error)

AddCustomAttributesToCustomer adds custom attributes to specific customer.

See https://dev.chartmogul.com/v1.0/reference#customer-attributes

func (API) AddCustomAttributesWithEmail

func (api API) AddCustomAttributesWithEmail(email string, customAttributes []*CustomAttribute) (*Customers, error)

AddCustomAttributesWithEmail adds custom attributes to customers with specific email.

See https://dev.chartmogul.com/v1.0/reference#customer-attributes

func (API) AddTagsToCustomer

func (api API) AddTagsToCustomer(customerUUID string, tags []string) (*TagsResult, error)

AddTagsToCustomer gives customer new tags.

See https://dev.chartmogul.com/v1.0/reference#tags

func (API) AddTagsToCustomersWithEmail

func (api API) AddTagsToCustomersWithEmail(email string, tags []string) (*Customers, error)

AddTagsToCustomersWithEmail gives new tags to (multiple) customers identified by e-mail only.

See https://dev.chartmogul.com/v1.0/reference#tags

func (API) CancelSubscription

func (api API) CancelSubscription(subscriptionUUID string, cancelSubscriptionParams *CancelSubscriptionParams) (*Subscription, error)

CancelSubscription creates an Import API Data Source in ChartMogul.

See https://dev.chartmogul.com/v1.0/reference#subscriptions

func (API) ConnectSubscriptions added in v1.1.7

func (api API) ConnectSubscriptions(customerUUID string, subscriptions []Subscription) error

ConnectSubscriptions connects two subscription objects

See https://dev.chartmogul.com/reference#connect-subscriptions

func (API) CreateCustomer

func (api API) CreateCustomer(newCustomer *NewCustomer) (*Customer, error)

CreateCustomer loads the customer to Chartmogul. New endpoint - with attributes.

See https://dev.chartmogul.com/v1.0/reference#customers

func (API) CreateDataSource

func (api API) CreateDataSource(name string) (*DataSource, error)

CreateDataSource creates an API Data Source in ChartMogul.

See https://dev.chartmogul.com/v1.0/reference#data-sources

func (API) CreateDataSourceWithSystem added in v1.1.4

func (api API) CreateDataSourceWithSystem(dataSource *DataSource) (*DataSource, error)

CreateDataSourceWithSystem creates an API Data Source in ChartMogul. * Allows other parameters than just the name.

See https://dev.chartmogul.com/v1.0/reference#data-sources

func (API) CreateInvoices

func (api API) CreateInvoices(invoices []*Invoice, customerUUID string) (*Invoices, error)

CreateInvoices loads an invoice to a customer in Chartmogul. Customer must have a valid UUID! (use return value of API)

See https://dev.chartmogul.com/v1.0/reference#invoices

func (API) CreatePlan

func (api API) CreatePlan(plan *Plan) (result *Plan, err error)

CreatePlan creates plan under given Data Source.

See https://dev.chartmogul.com/v1.0/reference#plans

func (API) CreateTransaction

func (api API) CreateTransaction(transaction *Transaction, invoiceUUID string) (*Transaction, error)

CreateTransaction loads an transaction to a customer in Chartmogul. Customer must have a valid UUID! (use return value of API)

See https://dev.chartmogul.com/v1.0/reference#transactions

func (API) DeleteCustomer

func (api API) DeleteCustomer(customerUUID string) error

DeleteCustomer deletes one customer by UUID.

See https://dev.chartmogul.com/v1.0/reference#customers

func (API) DeleteCustomerInvoices added in v1.1.4

func (api API) DeleteCustomerInvoices(dataSourceUUID, customerUUID string) error

DeleteCustomerInvoices deletes all customer's invoices by UUID for given data source UUID.

See https://dev.chartmogul.com/v1.0/reference#customers

func (API) DeleteDataSource

func (api API) DeleteDataSource(uuid string) error

DeleteDataSource deletes the data source identified by its UUID.

See https://dev.chartmogul.com/v1.0/reference#data-sources

func (API) DeleteInvoice added in v1.1.3

func (api API) DeleteInvoice(invoiceUUID string) error

DeleteInvoice deletes one invoice by UUID.

See https://dev.chartmogul.com/v1.0/reference#invoices

func (API) DeletePlan

func (api API) DeletePlan(planUUID string) error

DeletePlan deletes one plan by UUID.

See https://dev.chartmogul.com/v1.0/reference#plans

func (API) ListAllInvoices added in v1.1.2

func (api API) ListAllInvoices(listAllInvoicesParams *ListAllInvoicesParams) (*Invoices, error)

ListAllInvoices lists all imported invoices. Use parameters to narrow down the search/for paging. listAllInvoicesParams can be nil, in which case default values on API are used.

See https://dev.chartmogul.com/v1.0/reference#invoices

func (API) ListCustomers

func (api API) ListCustomers(listCustomersParams *ListCustomersParams) (*Customers, error)

ListCustomers lists all Customers for cutomer of given UUID.

See https://dev.chartmogul.com/v1.0/reference#customers

func (API) ListDataSources

func (api API) ListDataSources() (*DataSources, error)

ListDataSources lists all available Data Sources (no paging).

See https://dev.chartmogul.com/v1.0/reference#data-sources

func (API) ListDataSourcesWithFilters added in v1.1.4

func (api API) ListDataSourcesWithFilters(listDataSourcesParams *ListDataSourcesParams) (*DataSources, error)

ListDataSourcesWithFilters lists all available Data Sources (no paging). * Allows filtering.

See https://dev.chartmogul.com/v1.0/reference#data-sources

func (API) ListInvoices

func (api API) ListInvoices(cursor *Cursor, customerUUID string) (*Invoices, error)

ListInvoices lists all imported invoices for a customer.

See https://dev.chartmogul.com/v1.0/reference#invoices

func (API) ListPlans

func (api API) ListPlans(listPlansParams *ListPlansParams) (*Plans, error)

ListPlans returns list of plans.

See https://dev.chartmogul.com/v1.0/reference#plans

func (API) ListSubscriptions

func (api API) ListSubscriptions(cursor *Cursor, customerUUID string) (*Subscriptions, error)

ListSubscriptions lists all subscriptions for cutomer of given UUID.

See https://dev.chartmogul.com/v1.0/reference#subscriptions

func (API) MergeCustomers

func (api API) MergeCustomers(mergeCustomersParams *MergeCustomersParams) error

MergeCustomers merges two cutomers.

See https://dev.chartmogul.com/v1.0/reference#customers

func (API) MetricsListActivities

func (api API) MetricsListActivities(cursor *Cursor, customerUUID string) (*MetricsActivities, error)

MetricsListActivities lists all activities for cutomer of a given UUID.

See https://dev.chartmogul.com/v1.0/reference#list-customer-activities

func (API) MetricsListSubscriptions

func (api API) MetricsListSubscriptions(cursor *Cursor, customerUUID string) (*MetricsSubscriptions, error)

MetricsListSubscriptions lists all subscriptions for cutomer of a given UUID.

See https://dev.chartmogul.com/v1.0/reference#list-customer-subscriptions

func (API) MetricsRetrieveARPA

func (api API) MetricsRetrieveARPA(metricsFilter *MetricsFilter) (*ARPAResult, error)

MetricsRetrieveARPA retrieves the ARPA metrics, for the specified time period.

See https://dev.chartmogul.com/v1.0/reference#retrieve-arpa

func (API) MetricsRetrieveARR

func (api API) MetricsRetrieveARR(metricsFilter *MetricsFilter) (*ARRResult, error)

MetricsRetrieveARR retrieves the ARR metrics, for the specified time period.

See https://dev.chartmogul.com/v1.0/reference#retrieve-arr

func (API) MetricsRetrieveASP

func (api API) MetricsRetrieveASP(metricsFilter *MetricsFilter) (*ASPResult, error)

MetricsRetrieveASP retrieves the ASP metrics, for the specified time period.

See https://dev.chartmogul.com/v1.0/reference#retrieve-asp

func (API) MetricsRetrieveAll

func (api API) MetricsRetrieveAll(metricsFilter *MetricsFilter) (*MetricsResult, error)

MetricsRetrieveAll retrieves all key metrics, for the specified time period.

See https://dev.chartmogul.com/v1.0/reference#retrieve-all-key-metrics

func (API) MetricsRetrieveCustomerChurnRate

func (api API) MetricsRetrieveCustomerChurnRate(metricsFilter *MetricsFilter) (*CustomerChurnRateResult, error)

MetricsRetrieveCustomerChurnRate retrieves customer churn rate, for the specified time period.

See https://dev.chartmogul.com/v1.0/reference#retrieve-customer-churn-rate

func (API) MetricsRetrieveCustomerCount

func (api API) MetricsRetrieveCustomerCount(metricsFilter *MetricsFilter) (*CustomerCountResult, error)

MetricsRetrieveCustomerCount retrieves customer count, for the specified time period.

See https://dev.chartmogul.com/v1.0/reference#retrieve-customer-count

func (API) MetricsRetrieveLTV

func (api API) MetricsRetrieveLTV(metricsFilter *MetricsFilter) (*LTVResult, error)

MetricsRetrieveLTV retrieves LTV metrics, for the specified time period.

See https://dev.chartmogul.com/v1.0/reference#retrieve-ltv

func (API) MetricsRetrieveMRR

func (api API) MetricsRetrieveMRR(metricsFilter *MetricsFilter) (*MRRResult, error)

MetricsRetrieveMRR retrieves the MRR metrics, for the specified time period.

See https://dev.chartmogul.com/v1.0/reference#retrieve-mrr

func (API) MetricsRetrieveMRRChurnRate

func (api API) MetricsRetrieveMRRChurnRate(metricsFilter *MetricsFilter) (*MRRChurnRateResult, error)

MetricsRetrieveMRRChurnRate retrieves all key metrics, for the specified time period.

See https://dev.chartmogul.com/v1.0/reference#retrieve-mrr-churn-rate

func (API) Ping

func (api API) Ping() (bool, error)

Ping is the authentication test endpoint. Doesn't retry on 429.

See https://dev.chartmogul.com/v1.0/docs/authentication

func (API) PurgeDataSource added in v1.1.4

func (api API) PurgeDataSource(dataSourceUUID string) error

PurgeDataSource deletes all the data in the data source, but keeps the UUID.

See https://dev.chartmogul.com/v1.0/reference#data-sources

func (API) RemoveCustomAttributes

func (api API) RemoveCustomAttributes(customerUUID string, customAttributes []string) (*CustomAttributes, error)

RemoveCustomAttributes removes a list of custom attributes from a specific customer.

See https://dev.chartmogul.com/v1.0/reference#customer-attributes

func (API) RemoveTagsFromCustomer

func (api API) RemoveTagsFromCustomer(customerUUID string, tags []string) (*TagsResult, error)

RemoveTagsFromCustomer deletes passed tags from customer of given UUID.

See https://dev.chartmogul.com/v1.0/reference#tags

func (API) RetrieveCustomer

func (api API) RetrieveCustomer(customerUUID string) (*Customer, error)

RetrieveCustomer returns one customer as in API.

See https://dev.chartmogul.com/v1.0/reference#customers

func (API) RetrieveCustomersAttributes

func (api API) RetrieveCustomersAttributes(customerUUID string) (*Attributes, error)

RetrieveCustomersAttributes returns attributes for given customer UUID.

See https://dev.chartmogul.com/v1.0/reference#customer-attributes

func (API) RetrieveDataSource

func (api API) RetrieveDataSource(dataSourceUUID string) (*DataSource, error)

RetrieveDataSource returns one Data Source by UUID.

See https://dev.chartmogul.com/v1.0/reference#data-sources

func (API) RetrieveInvoice added in v1.1.3

func (api API) RetrieveInvoice(invoiceUUID string) (*Invoice, error)

RetrieveInvoice returns one Invoice by UUID.

See https://dev.chartmogul.com/v1.0/reference#invoices

func (API) RetrievePlan

func (api API) RetrievePlan(planUUID string) (*Plan, error)

RetrievePlan returns one plan by UUID.

See https://dev.chartmogul.com/v1.0/reference#plans

func (API) SearchCustomers

func (api API) SearchCustomers(searchCustomersParams *SearchCustomersParams) (*Customers, error)

SearchCustomers lists all Customers for cutomer of given UUID.

See https://dev.chartmogul.com/v1.0/reference#customers

func (*API) SetClient added in v1.1.4

func (api *API) SetClient(newClient *http.Client)

SetClient changes the client - for VCR integration tests.

func (API) UpdateCustomAttributesOfCustomer

func (api API) UpdateCustomAttributesOfCustomer(customerUUID string, customAttributes map[string]interface{}) (*CustomAttributes, error)

UpdateCustomAttributesOfCustomer updates custom attributes of a specific customer.

See https://dev.chartmogul.com/v1.0/reference#customer-attributes

func (API) UpdateCustomer

func (api API) UpdateCustomer(customer *Customer, customerUUID string) (*Customer, error)

UpdateCustomer updates one customer in API.

See https://dev.chartmogul.com/v1.0/reference#customers

func (API) UpdateCustomerV2 added in v1.1.6

func (api API) UpdateCustomerV2(input *UpdateCustomer, customerUUID string) (*Customer, error)

UpdateCustomerV2 updates one customer in API.

See https://dev.chartmogul.com/v1.0/reference#update-a-customer

func (API) UpdatePlan

func (api API) UpdatePlan(plan *Plan, planUUID string) (*Plan, error)

UpdatePlan returns list of plans.

See https://dev.chartmogul.com/v1.0/reference#plans

type ARPAMetrics

type ARPAMetrics struct {
	Date string  `json:"date"`
	ARPA float64 `json:"arpa"`
}

ARPAMetrics represents results of Metrics API.

type ARPAResult

type ARPAResult struct {
	Entries []*ARPAMetrics `json:"entries,omitempty"`
	Summary *Summary       `json:"summary"`
}

ARPAResult represents results of Metrics API.

type ARRMetrics

type ARRMetrics struct {
	Date string  `json:"date"`
	ARR  float64 `json:"arr"`
}

ARRMetrics represents results of Metrics API.

type ARRResult

type ARRResult struct {
	Entries []*ARRMetrics `json:"entries,omitempty"`
	Summary *Summary      `json:"summary"`
}

ARRResult represents results of Metrics API.

type ASPMetrics

type ASPMetrics struct {
	Date string  `json:"date"`
	ASP  float64 `json:"asp"`
}

ASPMetrics represents results of Metrics API.

type ASPResult

type ASPResult struct {
	Entries []*ASPMetrics `json:"entries,omitempty"`
	Summary *Summary      `json:"summary"`
}

ASPResult represents results of Metrics API.

type Address

type Address struct {
	AddressZIP string `json:"address_zip,omitempty"`
	City       string `json:"city,omitempty"`
	State      string `json:"state,omitempty"`
	Country    string `json:"country,omitempty"`
}

Address is subdocument of Customer.

type AllMetrics

type AllMetrics struct {
	Date              string  `json:"date"`
	CustomerChurnRate float64 `json:"customer-churn-rate"`
	MrrChurnRate      float64 `json:"mrr-churn-rate"`
	Ltv               float64 `json:"ltv"`
	Customers         uint32  `json:"customers"`
	Asp               float64 `json:"asp"`
	Arpa              float64 `json:"arpa"`
	Arr               float64 `json:"arr"`
	Mrr               float64 `json:"mrr"`
}

AllMetrics represents results of Metrics API.

type AttributeWithSource added in v1.1.1

type AttributeWithSource struct {
	Value  interface{} `json:"value"`
	Source string      `json:"source"`
}

AttributeWithSource covers the special case when you need to update customer's attribute and chage the source which shows in the ChartMogul UI.

type Attributes

type Attributes struct {
	Tags     []string               `json:"tags,omitempty"`
	Stripe   map[string]interface{} `json:"stripe,omitempty"`
	Clearbit map[string]interface{} `json:"clearbit,omitempty"`
	Custom   map[string]interface{} `json:"custom,omitempty"`
}

Attributes is subdocument of Customer.

type CancelSubscriptionParams

type CancelSubscriptionParams struct {
	CancelledAt       string    `json:"cancelled_at,omitempty"`
	CancellationDates *[]string `json:"cancellation_dates,omitempty"`
}

CancelSubscriptionParams represents arguments to be marshalled into JSON.

type Cursor

type Cursor struct {
	Page    uint32 `json:"page,omitempty"`
	PerPage uint32 `json:"per_page,omitempty"`
}

Cursor contains query parameters for paging in CM. Attributes for query must be string, because gorequest library cannot convert anything else.

type CustID

type CustID struct {
	DataSourceUUID string `json:"data_source_uuid,omitempty"`
	ExternalID     string `json:"external_id,omitempty"`
	CustomerUUID   string `json:"customer_uuid,omitempty"`
}

CustID - use either DataSourceUUID & ExternalID or CustomerUUID

type CustomAttribute

type CustomAttribute struct {
	Type   string      `json:"type"`
	Key    string      `json:"key"`
	Value  interface{} `json:"value"`
	Source string      `json:"source,omitempty"`
}

CustomAttribute = typed custom attribute.

type CustomAttributes

type CustomAttributes struct {
	Custom map[string]interface{} `json:"custom"`
}

CustomAttributes contains updated custom attributes.

type Customer

type Customer struct {
	ID uint32 `json:"id,omitempty"`
	// Basic info
	DataSourceUUID  string   `json:"data_source_uuid,omitempty"`
	DataSourceUUIDs []string `json:"data_source_uuids,omitempty"`
	UUID            string   `json:"uuid,omitempty"`
	ExternalID      string   `json:"external_id,omitempty"`
	ExternalIDs     []string `json:"external_ids,omitempty"`
	Name            string   `json:"name,omitempty"`
	Email           string   `json:"email,omitempty"`
	Status          string   `json:"status,omitempty"`
	CustomerSince   string   `json:"customer-since,omitempty"`

	Attributes *Attributes `json:"attributes,omitempty"`
	Address    *Address    `json:"address,omitempty"`

	// Other info
	Mrr               float64 `json:"mrr,omitempty"`
	Arr               float64 `json:"arr,omitempty"`
	BillingSystemURL  string  `json:"billing-system-url,omitempty"`
	ChartmogulURL     string  `json:"chartmogul-url,omitempty"`
	BillingSystemType string  `json:"billing-system-type,omitempty"`
	Currency          string  `json:"currency,omitempty"`
	CurrencySign      string  `json:"currency-sign,omitempty"`

	// For update
	Company            string `json:"company,omitempty"`
	Country            string `json:"country,omitempty"`
	State              string `json:"state,omitempty"`
	City               string `json:"city,omitempty"`
	Zip                string `json:"zip,omitempty"`
	LeadCreatedAt      string `json:"lead_created_at,omitempty"`
	FreeTrialStartedAt string `json:"free_trial_started_at,omitempty"`

	Errors Errors `json:"errors,omitempty"`
}

Customer is the customer as represented in the API.

type CustomerChurnRateMetrics

type CustomerChurnRateMetrics struct {
	Date              string  `json:"date"`
	CustomerChurnRate float64 `json:"customer-churn-rate"`
}

CustomerChurnRateMetrics represents results of Metrics API.

type CustomerChurnRateResult

type CustomerChurnRateResult struct {
	Entries []*CustomerChurnRateMetrics `json:"entries,omitempty"`
	Summary *Summary                    `json:"summary"`
}

CustomerChurnRateResult represents results of Metrics API.

type CustomerCountMetrics

type CustomerCountMetrics struct {
	Date      string `json:"date"`
	Customers uint32 `json:"customers"`
}

CustomerCountMetrics represents results of Metrics API.

type CustomerCountResult

type CustomerCountResult struct {
	Entries []*CustomerCountMetrics `json:"entries,omitempty"`
	Summary *Summary                `json:"summary"`
}

CustomerCountResult represents results of Metrics API.

type Customers

type Customers struct {
	Entries     []*Customer `json:"entries,omitempty"`
	Page        uint32      `json:"page"`
	PerPage     uint32      `json:"per_page"`
	HasMore     bool        `json:"has_more,omitempty"`
	CurrentPage int32       `json:"current_page,omitempty"`
	TotalPages  int32       `json:"total_pages,omitempty"`
}

Customers is result of listing customers in API.

type DataSource

type DataSource struct {
	UUID      string `json:"uuid"`
	Name      string `json:"name"`
	CreatedAt string `json:"created_at"`
	Status    string `json:"status"`
	System    string `json:"system"`
	Errors    Errors `json:"errors,omitempty"`
}

DataSource represents API data source in ChartMogul. See https://dev.chartmogul.com/v1.0/reference#list-data-sources

type DataSources

type DataSources struct {
	DataSources []*DataSource `json:"data_sources"`
}

DataSources is the result of listing data sources, but doesn't contain any paging.

type Errors

type Errors map[string]string

Errors contains error feedback from ChartMogul

func (Errors) Error

func (e Errors) Error() string

func (Errors) IsAlreadyExists

func (e Errors) IsAlreadyExists() (is bool)

IsAlreadyExists is helper that returns true, if there's only one error and it means the uploaded resource of the same external_id already exists.

func (Errors) IsInvoiceAndTransactionAlreadyExist

func (e Errors) IsInvoiceAndTransactionAlreadyExist() (is bool)

IsInvoiceAndTransactionAlreadyExist occurs when both invoice and tx exist already.

type HTTPError

type HTTPError interface {
	StatusCode() int
	Status() string
	Response() string
}

HTTPError is wrapper to easily handle HTTP states.

type IApi

type IApi interface {
	Ping() (res bool, err error)
	// Data sources
	CreateDataSource(name string) (*DataSource, error)
	CreateDataSourceWithSystem(dataSource *DataSource) (*DataSource, error)
	RetrieveDataSource(dataSourceUUID string) (*DataSource, error)
	ListDataSources() (*DataSources, error)
	ListDataSourcesWithFilters(listDataSourcesParams *ListDataSourcesParams) (*DataSources, error)
	PurgeDataSource(dataSourceUUID string) error
	DeleteDataSource(dataSourceUUID string) error
	// Invoices
	CreateInvoices(invoices []*Invoice, customerUUID string) (*Invoices, error)
	ListInvoices(cursor *Cursor, customerUUID string) (*Invoices, error)
	ListAllInvoices(listAllInvoicesParams *ListAllInvoicesParams) (*Invoices, error)
	RetrieveInvoice(invoiceUUID string) (*Invoice, error)
	DeleteInvoice(invoiceUUID string) error
	// Plans
	CreatePlan(plan *Plan) (result *Plan, err error)
	RetrievePlan(planUUID string) (*Plan, error)
	ListPlans(listPlansParams *ListPlansParams) (*Plans, error)
	UpdatePlan(plan *Plan, planUUID string) (*Plan, error)
	DeletePlan(planUUID string) error
	// Subscriptions
	CancelSubscription(subscriptionUUID string, cancelSubscriptionParams *CancelSubscriptionParams) (*Subscription, error)
	ListSubscriptions(cursor *Cursor, customerUUID string) (*Subscriptions, error)
	// Transactions
	CreateTransaction(transaction *Transaction, invoiceUUID string) (*Transaction, error)

	// Customers
	CreateCustomer(newCustomer *NewCustomer) (*Customer, error)
	RetrieveCustomer(customerUUID string) (*Customer, error)
	UpdateCustomer(Customer *Customer, customerUUID string) (*Customer, error)
	UpdateCustomerV2(Customer *UpdateCustomer, customerUUID string) (*Customer, error)
	ListCustomers(ListCustomersParams *ListCustomersParams) (*Customers, error)
	SearchCustomers(SearchCustomersParams *SearchCustomersParams) (*Customers, error)
	MergeCustomers(MergeCustomersParams *MergeCustomersParams) error
	DeleteCustomer(customerUUID string) error
	DeleteCustomerInvoices(dataSourceUUID, customerUUID string) error

	//  - Cusomer Attributes
	RetrieveCustomersAttributes(customerUUID string) (*Attributes, error)

	//  Tags
	AddTagsToCustomer(customerUUID string, tags []string) (*TagsResult, error)
	AddTagsToCustomersWithEmail(email string, tags []string) (*Customers, error)
	RemoveTagsFromCustomer(customerUUID string, tags []string) (*TagsResult, error)

	// Custom Attributes
	AddCustomAttributesToCustomer(customerUUID string, customAttributes []*CustomAttribute) (*CustomAttributes, error)
	AddCustomAttributesWithEmail(email string, customAttributes []*CustomAttribute) (*Customers, error)
	UpdateCustomAttributesOfCustomer(customerUUID string, customAttributes map[string]interface{}) (*CustomAttributes, error)
	RemoveCustomAttributes(customerUUID string, customAttributes []string) (*CustomAttributes, error)

	// Metrics
	MetricsRetrieveAll(metricsFilter *MetricsFilter) (*MetricsResult, error)
	MetricsRetrieveMRR(metricsFilter *MetricsFilter) (*MRRResult, error)
	MetricsRetrieveARR(metricsFilter *MetricsFilter) (*ARRResult, error)
	MetricsRetrieveARPA(metricsFilter *MetricsFilter) (*ARPAResult, error)
	MetricsRetrieveASP(metricsFilter *MetricsFilter) (*ASPResult, error)
	MetricsRetrieveCustomerCount(metricsFilter *MetricsFilter) (*CustomerCountResult, error)
	MetricsRetrieveCustomerChurnRate(metricsFilter *MetricsFilter) (*CustomerChurnRateResult, error)
	MetricsRetrieveMRRChurnRate(metricsFilter *MetricsFilter) (*MRRChurnRateResult, error)
	MetricsRetrieveLTV(metricsFilter *MetricsFilter) (*LTVResult, error)

	// Metrics - Subscriptions & Activities
	MetricsListSubscriptions(cursor *Cursor, customerUUID string) (*MetricsSubscriptions, error)
	MetricsListActivities(cursor *Cursor, customerUUID string) (*MetricsActivities, error)
}

IApi defines the interface of the library. Necessary eg. for mocks in testing.

type Invoice

type Invoice struct {
	UUID           string         `json:"uuid,omitempty"`
	CustomerUUID   string         `json:"customer_uuid,omitempty"`
	Currency       string         `json:"currency"`
	DataSourceUUID string         `json:"data_source_uuid,omitempty"`
	Date           string         `json:"date"`
	DueDate        string         `json:"due_date,omitempty"`
	ExternalID     string         `json:"external_id"`
	LineItems      []*LineItem    `json:"line_items"`
	Transactions   []*Transaction `json:"transactions,omitempty"`
	Errors         *Errors        `json:"errors,omitempty"`
}

Invoice is the data for ChartMogul to auto-generate subscriptions.

type Invoices

type Invoices struct {
	CustomerUUID string     `json:"customer_uuid,omitempty"`
	CurrentPage  uint32     `json:"current_page,omitempty"`
	TotalPages   uint32     `json:"total_pages,omitempty"`
	Error        string     `json:"error,omitempty"`
	Invoices     []*Invoice `json:"invoices"`
}

Invoices is wrapper for bulk importing invoices In case of /v1/invoices endpoint, the customer_uuid is on individual invoices and here it's empty.

type LTVMetrics

type LTVMetrics struct {
	Date string  `json:"date"`
	LTV  float64 `json:"ltv"`
}

LTVMetrics represents results of Metrics API.

type LTVResult

type LTVResult struct {
	Entries []*LTVMetrics `json:"entries,omitempty"`
	Summary *Summary      `json:"summary"`
}

LTVResult represents results of Metrics API.

type LineItem

type LineItem struct {
	UUID                   string `json:"uuid,omitempty"`
	AccountCode            string `json:"account_code,omitempty"`
	AmountInCents          int    `json:"amount_in_cents"`
	CancelledAt            string `json:"cancelled_at,omitempty"`
	Description            string `json:"description,omitempty"`
	DiscountAmountInCents  int    `json:"discount_amount_in_cents,omitempty"`
	DiscountCode           string `json:"discount_code,omitempty"`
	ExternalID             string `json:"external_id,omitempty"`
	PlanUUID               string `json:"plan_uuid,omitempty"`
	Prorated               bool   `json:"prorated,omitempty"`
	Quantity               int    `json:"quantity,omitempty"`
	ServicePeriodEnd       string `json:"service_period_end,omitempty"`
	ServicePeriodStart     string `json:"service_period_start,omitempty"`
	SubscriptionExternalID string `json:"subscription_external_id,omitempty"`
	SubscriptionUUID       string `json:"subscription_uuid,omitempty"`
	TaxAmountInCents       int    `json:"tax_amount_in_cents,omitempty"`
	TransactionFeesInCents int    `json:"transaction_fees_in_cents,omitempty"`
	Type                   string `json:"type"`
}

LineItem represents a singular items of the invoices

type ListAllInvoicesParams added in v1.1.2

type ListAllInvoicesParams struct {
	CustomerUUID   string `json:"customer_uuid,omitempty"`
	DataSourceUUID string `json:"data_source_uuid,omitempty"`
	ExternalID     string `json:"external_id,omitempty"`
	Cursor
}

ListAllInvoicesParams optional parameters for ListAllInvoices

type ListCustomersParams

type ListCustomersParams struct {
	DataSourceUUID string `json:"data_source_uuid,omitempty"`
	Status         string `json:"status,omitempty"`
	System         string `json:"system,omitempty"`
	ExternalID     string `json:"external_id,omitempty"`
	Cursor
}

ListCustomersParams = parameters for listing customers in API.

type ListDataSourcesParams added in v1.1.4

type ListDataSourcesParams struct {
	Name   string `json:"name,omitempty"`
	System string `json:"system,omitempty"`
}

ListDataSourcesParams are optional parameters for listing data sources.

type ListPlansParams

type ListPlansParams struct {
	DataSourceUUID string `json:"data_source_uuid"`
	ExternalID     string `json:"external_id,omitempty"`
	System         string `json:"system,omitempty"`
	Cursor
}

ListPlansParams = optional parameters for listing plans.

type MRRChurnRateMetrics

type MRRChurnRateMetrics struct {
	Date         string  `json:"date"`
	MRRChurnRate float64 `json:"mrr-churn-rate"`
}

MRRChurnRateMetrics represents results of Metrics API.

type MRRChurnRateResult

type MRRChurnRateResult struct {
	Entries []*MRRChurnRateMetrics `json:"entries,omitempty"`
	Summary *Summary               `json:"summary"`
}

MRRChurnRateResult represents results of Metrics API.

type MRRMetrics

type MRRMetrics struct {
	Date            string  `json:"date"`
	MRR             float64 `json:"mrr"`
	MRRNewBusiness  float64 `json:"mrr-new-business"`
	MRRExpansion    float64 `json:"mrr-expansion"`
	MRRContraction  float64 `json:"mrr-contraction"`
	MRRChurn        float64 `json:"mrr-churn"`
	MRRReactivation float64 `json:"mrr-reactivation"`
}

MRRMetrics represents results of Metrics API.

type MRRResult

type MRRResult struct {
	Entries []*MRRMetrics `json:"entries,omitempty"`
	Summary *Summary      `json:"summary"`
}

MRRResult represents results of Metrics API.

type MergeCustomersParams

type MergeCustomersParams struct {
	From CustID `json:"from"`
	Into CustID `json:"into"`
}

MergeCustomersParams - identify source and target for merging.

type MetricsActivities

type MetricsActivities struct {
	Entries []*MetricsActivity `json:"entries"`
	HasMore bool               `json:"has_more"`
	PerPage uint32             `json:"per_page"`
	Page    uint32             `json:"page"`
}

MetricsActivities is the result of listing activities in Metrics API.

type MetricsActivity

type MetricsActivity struct {
	ID                  uint64  `json:"id"`
	Date                string  `json:"date"`
	ActivityArr         float64 `json:"activity-arr"`
	ActivityMrr         float64 `json:"activity-mrr"`
	ActivityMrrMovement float64 `json:"activity-mrr-movement"`
	Currency            string  `json:"currency"`
	CurrencySign        string  `json:"currency-sign"`
	Description         string  `json:"description"`
	Type                string  `json:"type"`
}

MetricsActivity represents Metrics API activity in ChartMogul.

type MetricsFilter

type MetricsFilter struct {
	StartDate string `json:"start-date,omitempty"`
	EndDate   string `json:"end-date,omitempty"`
	Interval  string `json:"interval,omitempty"`
	Geo       string `json:"geo,omitempty"`
	Plans     string `json:"plans,omitempty"`
}

MetricsFilter convenient object to hold all filtering parameters.

type MetricsResult

type MetricsResult struct {
	Entries []*AllMetrics `json:"entries,omitempty"`
}

MetricsResult represents results of Metrics API.

type MetricsSubscription

type MetricsSubscription struct {
	ID                uint64  `json:"id"`
	ExternalID        string  `json:"external_id"`
	Plan              string  `json:"plan"`
	Quantity          uint32  `json:"quantity"`
	MRR               float64 `json:"mrr"`
	ARR               float64 `json:"arr"`
	Status            string  `json:"status"`
	BillingCycle      string  `json:"billing-cycle"`
	BillingCycleCount uint32  `json:"billing-cycle-count"`
	StartDate         string  `json:"start-date"`
	EndDate           string  `json:"end-date"`
	Currency          string  `json:"currency"`
	CurrencySign      string  `json:"currency-sign"`
}

MetricsSubscription represents Metrics API subscription in ChartMogul.

type MetricsSubscriptions

type MetricsSubscriptions struct {
	Entries []*MetricsSubscription `json:"entries"`
	HasMore bool                   `json:"has_more"`
	PerPage uint32                 `json:"per_page"`
	Page    uint32                 `json:"page"`
}

MetricsSubscriptions is the result of listing subscriptions in Metrics API.

type NewAttributes

type NewAttributes struct {
	Tags   []string           `json:"tags,omitempty"`
	Custom []*CustomAttribute `json:"custom,omitempty"`
}

NewAttributes is subdocument of NewCustomer.

type NewCustomer

type NewCustomer struct {
	// Obligatory
	DataSourceUUID string `json:"data_source_uuid"`
	ExternalID     string `json:"external_id,omitempty"`
	Name           string `json:"name,omitempty"`

	//Optional
	Email      string         `json:"email,omitempty"`
	Attributes *NewAttributes `json:"attributes,omitempty"`
	// Address
	Company string `json:"company,omitempty"`
	Country string `json:"country,omitempty"`
	State   string `json:"state,omitempty"`
	City    string `json:"city,omitempty"`
	Zip     string `json:"zip,omitempty"`
	// Lead/Trial
	LeadCreatedAt      string `json:"lead_created_at,omitempty"`
	FreeTrialStartedAt string `json:"free_trial_started_at,omitempty"`
}

NewCustomer allows creating customer on a new endpoint.

type Ping

type Ping struct {
	Data string
}

Ping is simple struct for the authentication test endpoint.

type Plan

type Plan struct {
	UUID           string `json:"uuid,omitempty"`
	DataSourceUUID string `json:"data_source_uuid,omitempty"`
	ExternalID     string `json:"external_id,omitempty"`
	Name           string `json:"name,omitempty"`
	IntervalCount  uint32 `json:"interval_count,omitempty"`
	IntervalUnit   string `json:"interval_unit,omitempty"`
	Errors         Errors `json:"errors,omitempty"`
}

Plan represents ChartMogul categorization of subscriptions.

type Plans

type Plans struct {
	Plans       []*Plan `json:"plans"`
	TotalPages  uint32  `json:"total_pages"`
	CurrentPage uint32  `json:"current_page"`
}

Plans is result of listing: plans + paging.

type RequestErrors

type RequestErrors interface {
	Errors() []error
}

RequestErrors wraps multiple request errors to normal 1 error struct.

type SearchCustomersParams

type SearchCustomersParams struct {
	Email string `json:"email,omitempty"`
	Cursor
}

SearchCustomersParams - just email now.

type Subscription

type Subscription struct {
	UUID              string   `json:"uuid,omitempty"`
	ExternalID        string   `json:"external_id"`
	PlanUUID          string   `json:"plan_uuid,omitempty"`
	CustomerUUID      string   `json:"customer_uuid,omitempty"`
	DataSourceUUID    string   `json:"data_source_uuid"`
	CancellationDates []string `json:"cancellation_dates,omitempty"`
}

Subscription represents Import API subscription in ChartMogul.

type Subscriptions

type Subscriptions struct {
	Subscriptions []Subscription `json:"subscriptions"`
	CustomerUUID  string         `json:"customer_uuid,omitempty"`
	TotalPages    uint32         `json:"total_pages,omitempty"`
	CurrentPage   uint32         `json:"current_page,omitempty"`
}

Subscriptions is the result of listing subscriptions with paging.

type Summary

type Summary struct {
	Current          float64 `json:"current"`
	Previous         float64 `json:"previous"`
	PercentageChange float64 `json:"percentage-change"`
}

Summary represents results of Metrics API.

type TagsByEmail

type TagsByEmail struct {
	Email string   `json:"email"`
	Tags  []string `json:"tags"`
}

TagsByEmail = input for AddTagsToCustomersWithEmail

type TagsResult

type TagsResult struct {
	Tags []string `json:"tags"`
}

TagsResult is necessary for the the result of AddTags.

type Transaction

type Transaction struct {
	UUID       string `json:"uuid,omitempty"`
	Date       string `json:"date"`
	ExternalID string `json:"external_id,omitempty"`
	Result     string `json:"result"`
	Type       string `json:"type"`
	Errors     Errors `json:"errors,omitempty"`
}

Transaction is either payment/refund on an invoice, for its full value.

type UpdateCustomer added in v1.1.6

type UpdateCustomer struct {
	Name               *string     `json:"name,omitempty"`
	Email              *string     `json:"email,omitempty"`
	Company            *string     `json:"company,omitempty"`
	Country            *string     `json:"country,omitempty"`
	State              *string     `json:"state,omitempty"`
	City               *string     `json:"city,omitempty"`
	Zip                *string     `json:"zip,omitempty"`
	LeadCreatedAt      *string     `json:"lead_created_at,omitempty"`
	FreeTrialStartedAt *string     `json:"free_trial_started_at,omitempty"`
	Attributes         *Attributes `json:"attributes,omitempty"`
}

UpdateCustomer allows updating customer on the update endpoint.

Directories

Path Synopsis
Package mock_chartmogul_go is a generated GoMock package.
Package mock_chartmogul_go is a generated GoMock package.

Jump to

Keyboard shortcuts

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