zuora

package module
v0.0.0-...-78abf31 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2019 License: MIT Imports: 13 Imported by: 0

README

Build Status

A Go client library to consume Zuora API.

This is a WIP and has minimal endpoints covered but it is really easy to add new ones.

Requirements

  • Go >1.7
  • Zuora client ID (Use Environment variables as best practice)
  • Zuora client secret (Use Environment variables as best practice)
  • Zuora api url (Use Environment variables as best practice)

Basic usage

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/hyeomans/zuora"
	"github.com/joho/godotenv"
)

func main() {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	zuoraClientID := os.Getenv("ZUORA_CLIENT_ID")
	zuoraClientSecret := os.Getenv("ZUORA_CLIENT_SECRET")
	zuoraURL := os.Getenv("ZUORA_URL")

	zuoraAPI := zuora.NewAPI(&http.Client{}, zuoraURL, zuoraClientID, zuoraClientSecret)
	ctx := context.Background()

	object, err := zuoraAPI.AccountsService.Summary(ctx, "customerAccount")

	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Printf("%+v\n", object)
	}
}

Declaring a custom http client.

package main

import (
	"context"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"time"

	"github.com/hyeomans/zuora"
	"github.com/joho/godotenv"
)

func main() {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	zuoraClientID := os.Getenv("ZUORA_CLIENT_ID")
	zuoraClientSecret := os.Getenv("ZUORA_CLIENT_SECRET")
	zuoraURL := os.Getenv("ZUORA_URL")
	httpClient := newHTTPClient()

	zuoraAPI := zuora.NewAPI(httpClient, zuoraURL, zuoraClientID, zuoraClientSecret)
	ctx := context.Background()

	object, err := zuoraAPI.AccountsService.Summary(ctx, "customerAccount")

	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Printf("%+v\n", object)
	}
}

func newHTTPClient() *http.Client {
	keepAliveTimeout := 600 * time.Second
	timeout := 2 * time.Second
	defaultTransport := &http.Transport{
		Dial: (&net.Dialer{
			KeepAlive: keepAliveTimeout,
		}).Dial,
		MaxIdleConns:        100,
		MaxIdleConnsPerHost: 100,
	}

	return &http.Client{
		Transport: defaultTransport,
		Timeout:   timeout,
	}
}

Declaring a custom Token Store

By default this package uses an in-memory backing store, but you can bring your own backing store, you only need to fullfill the interface:

//TokenStorer handles token renewal with two simple methods.
//Token() returns a boolean to indicate a token is valid and if valid, it will return the active token.
//Update() causes a side-effect to update a token in whichever backing store you choose.
type TokenStorer interface {
	Token() (bool, *Token)
	Update(*Token)
}

Error Handling

Zuora API is not consistent with their error responses, this package tries to unify all error responses in a single one. One of the most important error responses from Zuora is Request exceeded limit and this package follows "Errors as behaviour" to identify when this happens.

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/hyeomans/zuora"
	"github.com/joho/godotenv"
)

func main() {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	zuoraClientID := os.Getenv("ZUORA_CLIENT_ID")
	zuoraClientSecret := os.Getenv("ZUORA_CLIENT_SECRET")
	zuoraURL := os.Getenv("ZUORA_URL")

	zuoraAPI := zuora.NewAPI(&http.Client{}, zuoraURL, zuoraClientID, zuoraClientSecret)
	ctx := context.Background()

	object, err := zuoraAPI.AccountsService.Summary(ctx, "customerAccount")

	if err != nil {
    temporary, ok := result.(err)
    if ok && temporary.Temporary() {
      fmt.Println("You could continue making requests after cool off time")
    } else if ok && temporary.Temporary() {
      log.Fatal("This is not a temporary error, modify your request")
    } else {
      log.Fatalf("an error ocurred %v", err)
    }
	} else {
		fmt.Printf("%+v\n", object)
	}
}

Errors that are temporary according to this package are:

http.StatusTooManyRequests
http.StatusLocked
http.StatusInternalServerError

More about error as behaviour: https://dave.cheney.net/2014/12/24/inspecting-errors https://www.ardanlabs.com/blog/2014/10/error-handling-in-go-part-i.html

Error ordering

There could be a possibilty to that a response has multiple error messages encoded as described by Zuora documentation:

If the JSON success field is false, a JSON "reasons" array is included in the response body with at least one set of code and message attributes that can be used to code a response.

Example:

{

  "success": false,
  "processId": "3F7EA3FD706C7E7C",
  "reasons":  [
    {
      "code": 53100020,
      "message": " {com.zuora.constraints.either_or_both}"
    },
    {
      "code": 53100320,
      "message": "'termType' value should be one of: TERMED, EVERGREEN"
    }
  ]
}

The problem this presents is that, if you have a Request exceeded limit inside here, you might take different approaches to handle it. This package resolves this issue be setting a priority on errors, here is the list from highest (top) to lowest priority (bottom):

http.StatusTooManyRequests
http.StatusUnauthorized
http.StatusForbidden
http.StatusNotFound
http.StatusLocked
http.StatusInternalServerError
http.StatusBadRequest //<-- If not in list, is considered a BadRequest

ZOQL

Zuora allows to query tables by using a query language they call ZOQL, this package contains a helper struct/function to make easier to query whatever table you want.

All Products example

Here is an example where:

  • We wrap the API client
  • Create a custom struct to Unmarshal the raw response from our Query endpoint:
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/hyeomans/zuora"
	"github.com/joho/godotenv"
)

func main() {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	zuoraClientID := os.Getenv("ZUORA_CLIENT_ID")
	zuoraClientSecret := os.Getenv("ZUORA_CLIENT_SECRET")
	zuoraURL := os.Getenv("ZUORA_URL")

	zuoraAPI := zuora.NewAPI(&http.Client{}, zuoraURL, zuoraClientID, zuoraClientSecret)
	ctx := context.Background()

	myWrapper := myZuoraClient{zuoraAPI: zuoraAPI}

	products, err := myWrapper.GetProducts(ctx)

	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Printf("%+v\n", products)
	}
}

type myZuoraClient struct {
	zuoraAPI *zuora.API
}

type products struct {
	Records []zuora.Product `json:"records"`
}

//GetProducts Returns all products
func (m *myZuoraClient) GetProducts(ctx context.Context) ([]zuora.Product, error) {
	fields := []string{"ID", "Name"}
	zoqlComposer := zuora.NewZoqlComposer("Product", fields)
	rawProducts, err := m.zuoraAPI.ActionsService.Query(ctx, zoqlComposer)

	if err != nil {
		return nil, err
	}

	jsonResponse := products{}

	if err := json.Unmarshal(rawProducts, &jsonResponse); err != nil {
		return nil, err
	}

	return jsonResponse.Records, nil
}
Filtering example

ZoqlComposer uses functional options that allow you to compose a query that require:

  • Single filter
  • OR Filter
  • AND filter
  • Combination of those 3

Here is a minimal example:

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/hyeomans/zuora"
	"github.com/joho/godotenv"
)

func main() {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	zuoraClientID := os.Getenv("ZUORA_CLIENT_ID")
	zuoraClientSecret := os.Getenv("ZUORA_CLIENT_SECRET")
	zuoraURL := os.Getenv("ZUORA_URL")

	zuoraAPI := zuora.NewAPI(&http.Client{}, zuoraURL, zuoraClientID, zuoraClientSecret)
	ctx := context.Background()

	myWrapper := myZuoraClient{zuoraAPI: zuoraAPI}

	products, err := myWrapper.GetProductById(ctx, "an-id")

	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Printf("%+v\n", products)
	}
}

type myZuoraClient struct {
	zuoraAPI *zuora.API
}

type products struct {
	Records []zuora.Product `json:"records"`
}

//GetProductById Will return a product by ID with many filters.
func (m *myZuoraClient) GetProductById(ctx context.Context, id string) ([]zuora.Product, error) {
	fields := []string{"ID", "Name"}
	filter := zuora.QueryFilter{Key: "ID", Value: id}
	singleFilter := zuora.QueryWithFilter(filter)
	andFilter := zuora.QueryWithAndFilter([]zuora.QueryFilter{filter, filter})
	orFilter := zuora.QueryWithOrFilter([]zuora.QueryFilter{filter, filter})
	zoqlComposer := zuora.NewZoqlComposer("Product", fields, singleFilter, andFilter, orFilter)
	fmt.Println(zoqlComposer) //You can print to see returning query.
	//{ "queryString" : "select ID, Name from Product where ID = 'an-id'  and  ID = 'an-id' and ID = 'an-id'  or  ID = 'an-id' or ID = 'an-id'" }
	rawProducts, err := m.zuoraAPI.ActionsService.Query(ctx, zoqlComposer)

	if err != nil {
		return nil, err
	}

	jsonResponse := products{}

	if err := json.Unmarshal(rawProducts, &jsonResponse); err != nil {
		return nil, err
	}

	return jsonResponse.Records, nil
}

Available endpoints

Accounts

Zuora reference How to call it Link
Get account summary AccountsService.Summary(...) https://www.zuora.com/developer/api-reference/#operation/GET_AccountSummary

Actions

Zuora reference How to call it Link
Query ActionsService.Query(...) https://www.zuora.com/developer/api-reference/#operation/Action_POSTquery

Billing Documents

Zuora reference How to call it Link
Get billing documents BillingDocumentsService.Get(...) https://www.zuora.com/developer/api-reference/#operation/GET_BillingDocuments

Describe

Zuora reference How to call it Link
Describe object DescribeService.Model(...) https://www.zuora.com/developer/api-reference/#tag/Describe

Payments

Zuora reference How to call it Link
CRUD: Get payment PaymentsService.ByIdThroughObject https://www.zuora.com/developer/api-reference/#operation/Object_GETPayment

Products

Zuora reference How to call it Link
CRUD: Retrieve Product ProductsService.Get(...) https://www.zuora.com/developer/api-reference/#operation/Object_GETProduct

Subscriptions

Zuora reference How to call it Link
Get subscriptions by account SubscriptionsService.ByKey(...) https://www.zuora.com/developer/api-reference/#operation/GET_SubscriptionsByKey
CRUD: Retrieve Subscription SubscriptionsService.ByAccount(...) https://www.zuora.com/developer/api-reference/#operation/Object_GETSubscription
CRUD: Update Subscription SubscriptionsService.Update(...) https://www.zuora.com/developer/api-reference/#operation/Object_PUTSubscription
CRUD: Update Subscription SubscriptionsService.UpdateFull(...) https://www.zuora.com/developer/api-reference/#operation/Object_PUTSubscription
Cancel subscription SubscriptionsService.Cancel(...) https://www.zuora.com/developer/api-reference/#operation/PUT_CancelSubscription

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type API

type API struct {
	TokenService            *TokenService //TODO: Should this be public?
	BillingDocumentsService *BillingDocumentsService
	ProductsService         *ProductsService
	ActionsService          *ActionsService
	DescribeService         *DescribeService
	ProductRatePlansService *ProductRatePlansService
	AccountsService         *AccountsService
	SubscriptionsService    *SubscriptionsService
	PaymentsService         *PaymentsService
	ObjectModel             ObjectModel
}

API is a container struct with access to all underlying services

func NewAPI

func NewAPI(httpClient *http.Client, baseURL, clientID, clientSecret string, options ...ConfigOption) *API

NewAPI helper function to create all required services to interact with Zuora

type AccountSummary

type AccountSummary struct {
	Payments []struct {
		PaidInvoices []struct {
			InvoiceNumber        string  `json:"invoiceNumber"`
			AppliedPaymentAmount float64 `json:"appliedPaymentAmount"`
			InvoiceID            string  `json:"invoiceId"`
		} `json:"paidInvoices"`
		PaymentNumber string `json:"paymentNumber"`
		Status        string `json:"status"`
		EffectiveDate string `json:"effectiveDate"`
		ID            string `json:"id"`
		PaymentType   string `json:"paymentType"`
	} `json:"payments"`
	Invoices []struct {
		Amount        float64 `json:"amount"`
		Status        string  `json:"status"`
		InvoiceNumber string  `json:"invoiceNumber"`
		InvoiceDate   string  `json:"invoiceDate"`
		Balance       float64 `json:"balance"`
		ID            string  `json:"id"`
		DueDate       string  `json:"dueDate"`
	} `json:"invoices"`
	Usage []struct {
		UnitOfMeasure string `json:"unitOfMeasure"`
		Quantity      int    `json:"quantity"`
		StartDate     string `json:"startDate"`
	} `json:"usage"`
	BasicInfo struct {
		DefaultPaymentMethod struct {
			CreditCardNumber          string `json:"creditCardNumber"`
			PaymentMethodType         string `json:"paymentMethodType"`
			CreditCardExpirationMonth int    `json:"creditCardExpirationMonth"`
			CreditCardExpirationYear  int    `json:"creditCardExpirationYear"`
			CreditCardType            string `json:"creditCardType"`
			ID                        string `json:"id"`
		} `json:"defaultPaymentMethod"`
		Status                    string   `json:"status"`
		LastInvoiceDate           string   `json:"lastInvoiceDate"`
		LastPaymentAmount         float64  `json:"lastPaymentAmount"`
		BillCycleDay              int      `json:"billCycleDay"`
		InvoiceDeliveryPrefsPrint bool     `json:"invoiceDeliveryPrefsPrint"`
		InvoiceDeliveryPrefsEmail bool     `json:"invoiceDeliveryPrefsEmail"`
		AdditionalEmailAddresses  []string `json:"additionalEmailAddresses"`
		Name                      string   `json:"name"`
		Balance                   float64  `json:"balance"`
		AccountNumber             string   `json:"accountNumber"`
		ID                        string   `json:"id"`
		Currency                  string   `json:"currency"`
		LastPaymentDate           string   `json:"lastPaymentDate"`
	} `json:"basicInfo"`
	SoldToContact struct {
		Fax       string `json:"fax"`
		TaxRegion string `json:"taxRegion"`
		Country   string `json:"country"`
		ZipCode   string `json:"zipCode"`
		County    string `json:"county"`
		LastName  string `json:"lastName"`
		WorkEmail string `json:"workEmail"`
		State     string `json:"state"`
		Address2  string `json:"address2"`
		Address1  string `json:"address1"`
		FirstName string `json:"firstName"`
		ID        string `json:"id"`
		WorkPhone string `json:"workPhone"`
		City      string `json:"city"`
	} `json:"soldToContact"`
	Success       bool `json:"success"`
	Subscriptions []struct {
		TermEndDate           string `json:"termEndDate"`
		TermStartDate         string `json:"termStartDate"`
		Status                string `json:"status"`
		InitialTerm           int    `json:"initialTerm"`
		AutoRenew             bool   `json:"autoRenew"`
		SubscriptionNumber    string `json:"subscriptionNumber"`
		SubscriptionStartDate string `json:"subscriptionStartDate"`
		ID                    string `json:"id"`
		RatePlans             []struct {
			ProductName  string `json:"productName"`
			RatePlanName string `json:"ratePlanName"`
		} `json:"ratePlans"`
		TermType    string `json:"termType"`
		RenewalTerm int    `json:"renewalTerm"`
	} `json:"subscriptions"`
	BillToContact struct {
		Fax       string `json:"fax"`
		TaxRegion string `json:"taxRegion"`
		Country   string `json:"country"`
		ZipCode   string `json:"zipCode"`
		County    string `json:"county"`
		LastName  string `json:"lastName"`
		WorkEmail string `json:"workEmail"`
		State     string `json:"state"`
		Address2  string `json:"address2"`
		Address1  string `json:"address1"`
		FirstName string `json:"firstName"`
		ID        string `json:"id"`
		WorkPhone string `json:"workPhone"`
		City      string `json:"city"`
	} `json:"billToContact"`
}

type AccountsService

type AccountsService struct {
	// contains filtered or unexported fields
}

func (*AccountsService) Summary

func (s *AccountsService) Summary(ctx context.Context, objectID string) (AccountSummary, error)

Summary Retrieves detailed information about the specified customer account. The response includes the account information and a summary of the account’s subscriptions, invoices, payments, and usages for the last six recently updated subscriptions. NOTE: Returns only the six most recent subscriptions based on the subscription updatedDate. Within those subscriptions, there may be many rate plans and many rate plan charges. These items are subject to the maximum limit on the array size.

type ActionsService

type ActionsService struct {
	// contains filtered or unexported fields
}

func (*ActionsService) Query

func (s *ActionsService) Query(ctx context.Context, querier Querier) ([]byte, error)

type BillingDocuments

type BillingDocuments struct {
	ID             string `json:"id"`
	DocumentType   string `json:"documentType"`
	DocumentNumber string `json:"documentNumber"`
	DocumentDate   string `json:"documentDate"`
	Amount         int    `json:"amount"`
	Balance        int    `json:"balance"`
	AccountID      string `json:"accountId"`
	Status         string `json:"status"`
}

type BillingDocumentsService

type BillingDocumentsService struct {
	// contains filtered or unexported fields
}

func (*BillingDocumentsService) Get

func (s *BillingDocumentsService) Get(ctx context.Context, accountID string, queryParams ...string) ([]BillingDocuments, error)

type CancellationPolicy

type CancellationPolicy string

CancellationPolicy Cancellation method

const EndOfCurrentTerm CancellationPolicy = "EndOfCurrentTerm"

EndOfCurrentTerm is a valid cancellation policy in payload

const EndOfLastInvoicePeriod CancellationPolicy = "EndOfLastInvoicePeriod"

EndOfLastInvoicePeriod is a valid cancellation policy in payload

const SpecificDate CancellationPolicy = "SpecificDate"

SpecificDate is a valid cancellation policy in payload

type Config

type Config struct {
	HTTPClient   *http.Client
	BaseURL      string
	ClientID     string
	ClientSecret string
	// contains filtered or unexported fields
}

Config is the base configuration to return ZuoraApi

type ConfigOption

type ConfigOption func(*Config)

ConfigOption helper function to modify current Config struct

func WithTokenStorer

func WithTokenStorer(tokenStorer TokenStorer) ConfigOption

type DescribeService

type DescribeService struct {
	// contains filtered or unexported fields
}

DescribeService access to describe endpoint. Don't use in production or use at your own risk

func (*DescribeService) Model

func (s *DescribeService) Model(ctx context.Context, objectName ObjecName) (string, error)

Model returns useful information about a Zuora Object

func (*DescribeService) ModelNonCustom

func (s *DescribeService) ModelNonCustom(ctx context.Context, objectName ObjecName) (string, error)

ModelNonCustom returns only original fields in Zuora object

type ObjecName

type ObjecName string

ObjecName represents name of zuora object

type ObjectModel

type ObjectModel struct {
	Account                                  ObjecName
	AccountingCode                           ObjecName
	AccountingPeriod                         ObjecName
	Amendment                                ObjecName
	BillingRun                               ObjecName
	Contact                                  ObjecName
	ContactSnapshot                          ObjecName
	CreditBalanceAdjustment                  ObjecName
	CreditMemo                               ObjecName
	CreditMemoApplication                    ObjecName
	CreditMemoApplicationItem                ObjecName
	CreditMemoItem                           ObjecName
	CreditMemoPart                           ObjecName
	CreditMemoPartItem                       ObjecName
	CreditTaxationItem                       ObjecName
	FXCustomRate                             ObjecName
	DebitMemo                                ObjecName
	DebitMemoItem                            ObjecName
	DebitTaxationItem                        ObjecName
	DiscountAppliedMetrics                   ObjecName
	Tenant                                   ObjecName
	PaymentGatewayReconciliationEventLog     ObjecName
	PaymentReconciliationJob                 ObjecName
	PaymentReconciliationLog                 ObjecName
	Invoice                                  ObjecName
	InvoiceAdjustment                        ObjecName
	InvoiceItem                              ObjecName
	InvoiceItemAdjustment                    ObjecName
	InvoicePayment                           ObjecName
	JournalEntry                             ObjecName
	JournalEntryItem                         ObjecName
	JournalRun                               ObjecName
	Order                                    ObjecName
	OrderAction                              ObjecName
	OrderElp                                 ObjecName
	OrderItem                                ObjecName
	OrderMrr                                 ObjecName
	OrderQuantity                            ObjecName
	OrderTcb                                 ObjecName
	OrderTcv                                 ObjecName
	Payment                                  ObjecName
	PaymentApplication                       ObjecName
	PaymentApplicationItem                   ObjecName
	PaymentMethod                            ObjecName
	PaymentMethodSnapshot                    ObjecName
	PaymentMethodTransactionLog              ObjecName
	UpdaterDetail                            ObjecName
	PaymentPart                              ObjecName
	PaymentPartItem                          ObjecName
	PaymentRun                               ObjecName
	PaymentTransactionLog                    ObjecName
	ProcessedUsage                           ObjecName
	Product                                  ObjecName
	ProductRatePlan                          ObjecName
	ProductRatePlanCharge                    ObjecName
	ProductRatePlanChargeTier                ObjecName
	RatePlan                                 ObjecName
	RatePlanCharge                           ObjecName
	RatePlanChargeTier                       ObjecName
	Refund                                   ObjecName
	RefundApplication                        ObjecName
	RefundApplicationItem                    ObjecName
	RefundInvoicePayment                     ObjecName
	RefundPart                               ObjecName
	RefundPartItem                           ObjecName
	RefundTransactionLog                     ObjecName
	RevenueChargeSummary                     ObjecName
	RevenueChargeSummaryItem                 ObjecName
	RevenueEvent                             ObjecName
	RevenueEventCreditMemoItem               ObjecName
	RevenueEventDebitMemoItem                ObjecName
	RevenueEventInvoiceItem                  ObjecName
	RevenueEventInvoiceItemAdjustment        ObjecName
	RevenueEventItem                         ObjecName
	RevenueEventItemCreditMemoItem           ObjecName
	RevenueEventItemDebitMemoItem            ObjecName
	RevenueEventItemInvoiceItem              ObjecName
	RevenueEventItemInvoiceItemAdjustment    ObjecName
	RevenueEventType                         ObjecName
	RevenueSchedule                          ObjecName
	RevenueScheduleCreditMemoItem            ObjecName
	RevenueScheduleDebitMemoItem             ObjecName
	RevenueScheduleInvoiceItem               ObjecName
	RevenueScheduleInvoiceItemAdjustment     ObjecName
	RevenueScheduleItem                      ObjecName
	RevenueScheduleItemCreditMemoItem        ObjecName
	RevenueScheduleItemDebitMemoItem         ObjecName
	RevenueScheduleItemInvoiceItem           ObjecName
	RevenueScheduleItemInvoiceItemAdjustment ObjecName
	Subscription                             ObjecName
	TaxableItemSnapshot                      ObjecName
	TaxationItem                             ObjecName
	UpdaterBatch                             ObjecName
	Usage                                    ObjecName
}

ObjectModel container struct for all Zuora objects

type Payment

type Payment struct {
	PaymentNumber              string  `json:"PaymentNumber"`
	GatewayResponse            string  `json:"GatewayResponse"`
	ID                         string  `json:"Id"`
	UpdatedDate                string  `json:"UpdatedDate"`
	GatewayState               string  `json:"GatewayState"`
	Source                     string  `json:"Source"`
	AccountID                  string  `json:"AccountId"`
	BankIdentificationNumber   string  `json:"BankIdentificationNumber"`
	ReferenceID                string  `json:"ReferenceId"`
	PaymentMethodSnapshotID    string  `json:"PaymentMethodSnapshotId"`
	UpdatedByID                string  `json:"UpdatedById"`
	SubmittedOn                string  `json:"SubmittedOn"`
	Type                       string  `json:"Type"`
	CreatedDate                string  `json:"CreatedDate"`
	RefundAmount               int     `json:"RefundAmount"`
	SourceName                 string  `json:"SourceName"`
	Amount                     float64 `json:"Amount"`
	PaymentMethodID            string  `json:"PaymentMethodId"`
	CreatedByID                string  `json:"CreatedById"`
	Status                     string  `json:"Status"`
	AppliedCreditBalanceAmount int     `json:"AppliedCreditBalanceAmount"`
	Gateway                    string  `json:"Gateway"`
	GatewayResponseCode        string  `json:"GatewayResponseCode"`
	EffectiveDate              string  `json:"EffectiveDate"`
}

type PaymentsService

type PaymentsService struct {
	// contains filtered or unexported fields
}

PaymentsService Access all methods related to Payments

func (*PaymentsService) ByIdThroughObject

func (s *PaymentsService) ByIdThroughObject(ctx context.Context, id string) (Payment, error)

type Product

type Product struct {
	ID                 string `json:"Id"`
	Category           string `json:"Category,omitempty"`
	CreatedDate        string `json:"CreatedDate"`
	Name               string `json:"Name"`
	SKU                string `json:"SKU"`
	UpdatedDate        string `json:"UpdatedDate"`
	EffectiveStartDate string `json:"EffectiveStartDate"`
	UpdatedByID        string `json:"UpdatedById"`
	EffectiveEndDate   string `json:"EffectiveEndDate"`
	CreatedByID        string `json:"CreatedById"`
	Description        string `json:"Description,omitempty"`
}

Product with default fields from Zuora. It does not include custom fields.

type ProductRatePlan

type ProductRatePlan struct {
	ActiveCurrencies   string `json:"ActiveCurrencies,omitempty"`
	ProductID          string `json:"ProductId"`
	ID                 string `json:"Id"`
	CreatedByID        string `json:"CreatedById"`
	CreatedDate        string `json:"CreatedDate"`
	Name               string `json:"Name"`
	UpdatedDate        string `json:"UpdatedDate"`
	EffectiveStartDate string `json:"EffectiveStartDate"`
	UpdatedByID        string `json:"UpdatedById"`
	EffectiveEndDate   string `json:"EffectiveEndDate"`
	Description        string `json:"Description,omitempty"`
}

ProductRatePlan with default fields from Zuora. It does not include custom fields.

type ProductRatePlansService

type ProductRatePlansService struct {
	// contains filtered or unexported fields
}

type ProductsService

type ProductsService struct {
	// contains filtered or unexported fields
}

func (*ProductsService) Get

func (s *ProductsService) Get(ctx context.Context, objectID string) (Product, error)

type Querier

type Querier interface {
	Build() string
}

Querier One who, or that which, queries actions

type QueryFilter

type QueryFilter struct {
	Key   string
	Value string
}

QueryFilter key/value combination that represent filters.

type RatePlan

type RatePlan struct {
	ID                string           `json:"id"`
	LastChangeType    string           `json:"lastChangeType"`
	ProductID         string           `json:"productId"`
	ProductName       string           `json:"productName"`
	ProductSku        string           `json:"productSku"`
	ProductRatePlanID string           `json:"productRatePlanId"`
	RatePlanName      string           `json:"ratePlanName"`
	RatePlanCharges   []RatePlanCharge `json:"ratePlanCharges"`
}

type RatePlanCharge

type RatePlanCharge struct {
	ID                             string        `json:"id"`
	OriginalChargeID               string        `json:"originalChargeId"`
	ProductRatePlanChargeID        string        `json:"productRatePlanChargeId"`
	Number                         string        `json:"number"`
	Name                           string        `json:"name"`
	Type                           string        `json:"type"`
	Model                          string        `json:"model"`
	Uom                            interface{}   `json:"uom"`
	Version                        int           `json:"version"`
	PricingSummary                 string        `json:"pricingSummary"`
	PriceChangeOption              string        `json:"priceChangeOption"`
	PriceIncreasePercentage        interface{}   `json:"priceIncreasePercentage"`
	Currency                       string        `json:"currency"`
	Price                          float64       `json:"price"`
	Tiers                          interface{}   `json:"tiers"`
	IncludedUnits                  interface{}   `json:"includedUnits"`
	OveragePrice                   interface{}   `json:"overagePrice"`
	DiscountPercentage             interface{}   `json:"discountPercentage"`
	DiscountAmount                 interface{}   `json:"discountAmount"`
	ApplyDiscountTo                interface{}   `json:"applyDiscountTo"`
	DiscountLevel                  interface{}   `json:"discountLevel"`
	DiscountClass                  interface{}   `json:"discountClass"`
	DiscountApplyDetails           []interface{} `json:"discountApplyDetails"`
	BillingDay                     string        `json:"billingDay"`
	ListPriceBase                  string        `json:"listPriceBase"`
	BillingPeriod                  string        `json:"billingPeriod"`
	SpecificBillingPeriod          interface{}   `json:"specificBillingPeriod"`
	BillingTiming                  string        `json:"billingTiming"`
	BillingPeriodAlignment         string        `json:"billingPeriodAlignment"`
	Quantity                       float64       `json:"quantity"`
	SmoothingModel                 interface{}   `json:"smoothingModel"`
	NumberOfPeriods                interface{}   `json:"numberOfPeriods"`
	OverageCalculationOption       interface{}   `json:"overageCalculationOption"`
	OverageUnusedUnitsCreditOption interface{}   `json:"overageUnusedUnitsCreditOption"`
	UnusedUnitsCreditRates         interface{}   `json:"unusedUnitsCreditRates"`
	UsageRecordRatingOption        interface{}   `json:"usageRecordRatingOption"`
	Segment                        int           `json:"segment"`
	EffectiveStartDate             string        `json:"effectiveStartDate"`
	EffectiveEndDate               string        `json:"effectiveEndDate"`
	ProcessedThroughDate           interface{}   `json:"processedThroughDate"`
	ChargedThroughDate             interface{}   `json:"chargedThroughDate"`
	Done                           bool          `json:"done"`
	TriggerDate                    interface{}   `json:"triggerDate"`
	TriggerEvent                   string        `json:"triggerEvent"`
	EndDateCondition               string        `json:"endDateCondition"`
	UpToPeriodsType                interface{}   `json:"upToPeriodsType"`
	UpToPeriods                    interface{}   `json:"upToPeriods"`
	SpecificEndDate                interface{}   `json:"specificEndDate"`
	Mrr                            float64       `json:"mrr"`
	Dmrc                           float64       `json:"dmrc"`
	Tcv                            float64       `json:"tcv"`
	Dtcv                           float64       `json:"dtcv"`
	Description                    string        `json:"description"`
}

type Subscription

type Subscription struct {
	ID                        string     `json:"id"`
	AccountID                 string     `json:"accountId"`
	AccountNumber             string     `json:"accountNumber"`
	AccountName               string     `json:"accountName"`
	InvoiceOwnerAccountID     string     `json:"invoiceOwnerAccountId"`
	InvoiceOwnerAccountNumber string     `json:"invoiceOwnerAccountNumber"`
	InvoiceOwnerAccountName   string     `json:"invoiceOwnerAccountName"`
	SubscriptionNumber        string     `json:"subscriptionNumber"`
	TermType                  string     `json:"termType"`
	InvoiceSeparately         bool       `json:"invoiceSeparately"`
	ContractEffectiveDate     string     `json:"contractEffectiveDate"`
	ServiceActivationDate     string     `json:"serviceActivationDate"`
	CustomerAcceptanceDate    string     `json:"customerAcceptanceDate"`
	SubscriptionStartDate     string     `json:"subscriptionStartDate"`
	TermStartDate             string     `json:"termStartDate"`
	TermEndDate               string     `json:"termEndDate"`
	InitialTerm               int        `json:"initialTerm"`
	InitialTermPeriodType     string     `json:"initialTermPeriodType"`
	CurrentTerm               int        `json:"currentTerm"`
	CurrentTermPeriodType     string     `json:"currentTermPeriodType"`
	AutoRenew                 bool       `json:"autoRenew"`
	RenewalSetting            string     `json:"renewalSetting"`
	RenewalTerm               int        `json:"renewalTerm"`
	RenewalTermPeriodType     string     `json:"renewalTermPeriodType"`
	ContractedMrr             float64    `json:"contractedMrr"`
	TotalContractedValue      float64    `json:"totalContractedValue"`
	Notes                     string     `json:"notes"`
	Status                    string     `json:"status"`
	RatePlans                 []RatePlan `json:"ratePlans"`
}

type SubscriptionCancellationPayload

type SubscriptionCancellationPayload struct {
	CancellationPolicy CancellationPolicy `json:"cancellationPolicy"`
}

SubscriptionCancellationPayload payload to cancel a subscription

type SubscriptionCancellationResponse

type SubscriptionCancellationResponse struct {
	Success        bool    `json:"success"`
	SubscriptionID string  `json:"subscriptionId"`
	CancelledDate  string  `json:"cancelledDate"`
	TotalDeltaMrr  float64 `json:"totalDeltaMrr"`
	TotalDeltaTcv  float64 `json:"totalDeltaTcv"`
	InvoiceID      string  `json:"invoiceId"`
}

SubscriptionCancellationResponse response when cancelling a subscription

type SubscriptionChargeUpdateDetails

type SubscriptionChargeUpdateDetails []struct {
	Quantity         int    `json:"quantity"`
	RatePlanChargeID string `json:"ratePlanChargeId"`
}

SubscriptionChargeUpdateDetails is part of SubscriptionUpdate payload inside SubscriptionUpdate

type SubscriptionResponse

type SubscriptionResponse struct {
	Subscriptions []Subscription `json:"subscriptions"`
	Success       bool           `json:"success"`
}

type SubscriptionUpdate

type SubscriptionUpdate struct {
	ChargeUpdateDetails   []SubscriptionChargeUpdateDetails `json:"chargeUpdateDetails"`
	ContractEffectiveDate string                            `json:"contractEffectiveDate"`
	RatePlanID            string                            `json:"ratePlanId"`
}

SubscriptionUpdate is part of SubscriptionUpdate payload

type SubscriptionUpdateFullPayload

type SubscriptionUpdateFullPayload struct {
	AutoRenew             bool                 `json:"autoRenew"`
	Collect               bool                 `json:"collect"`
	CurrentTerm           string               `json:"currentTerm"`
	CurrentTermPeriodType string               `json:"currentTermPeriodType"`
	Notes                 string               `json:"notes"`
	RenewalSetting        string               `json:"renewalSetting"`
	RenewalTerm           string               `json:"renewalTerm"`
	RenewalTermPeriodType string               `json:"renewalTermPeriodType"`
	RunBilling            bool                 `json:"runBilling"`
	TermType              string               `json:"termType"`
	Updates               []SubscriptionUpdate `json:"update"`
}

SubscriptionUpdateFullPayload represents the full payload declared in Zuora documentation

type SubscriptionUpdateMinimalPayload

type SubscriptionUpdateMinimalPayload struct {
	Updates []SubscriptionUpdate `json:"update"`
}

SubscriptionUpdateMinimalPayload represents the minimal payload for updating a subscription

type SubscriptionUpdateResponse

type SubscriptionUpdateResponse struct {
	Success        bool    `json:"success"`
	SubscriptionID string  `json:"subscriptionId"`
	TotalDeltaMrr  float64 `json:"totalDeltaMrr"`
	TotalDeltaTcv  float64 `json:"totalDeltaTcv"`
}

SubscriptionUpdateResponse once a subscription is updated, it contains useful information

type SubscriptionsService

type SubscriptionsService struct {
	// contains filtered or unexported fields
}

SubscriptionsService Access all methods related to Subscriptions

func (*SubscriptionsService) ByAccount

func (s *SubscriptionsService) ByAccount(ctx context.Context, accountKey string) (SubscriptionResponse, error)

ByAccount Retrieves all subscriptions associated with the specified account. Zuora only returns the latest version of the subscriptions. Subscription data is returned in reverse chronological order based on updatedDate. accountKey possible values are: accountNumber or accountID https://www.zuora.com/developer/api-reference/#operation/Object_GETSubscription

func (*SubscriptionsService) ByKey

ByKey This REST API reference describes how to retrieve detailed information about a specified subscription in the latest version. https://www.zuora.com/developer/api-reference/#operation/GET_SubscriptionsByKey

func (*SubscriptionsService) Cancel

func (s *SubscriptionsService) Cancel(ctx context.Context, subscriptionKey string, subscriptionCancellationPayload SubscriptionCancellationPayload) (SubscriptionCancellationResponse, error)

Cancel use this to cancel an active subscription. https://www.zuora.com/developer/api-reference/#operation/PUT_CancelSubscription

func (*SubscriptionsService) Update

func (s *SubscriptionsService) Update(ctx context.Context, subscriptionKey string, subscriptionUpdatePayload SubscriptionUpdateMinimalPayload) (SubscriptionUpdateResponse, error)

Update contains the minimal update payload to apply to an accountKey https://www.zuora.com/developer/api-reference/#operation/Object_PUTSubscription

func (*SubscriptionsService) UpdateFull

func (s *SubscriptionsService) UpdateFull(ctx context.Context, subscriptionKey string, subscriptionUpdatePayload SubscriptionUpdateFullPayload) (SubscriptionUpdateResponse, error)

UpdateFull Use this call to make the following kinds of changes to a subscription: Add a note Change the renewal term or auto-renewal flag Change the term length or change between evergreen and termed Add a new product rate plan Remove an existing subscription rate plan Change the quantity or price of an existing subscription rate plan Notes: This feature is unavailable if you have the Orders feature enabled. See Orders Migration Guidance for more information. The Update Subscription call creates a new subscription, which has the old subscription number but a new subscription ID. The old subscription is canceled but remains in the system. In one request, this call can make: Up to 9 combined add, update, and remove changes No more than 1 change to terms & conditions Updates are performed in the following sequence: First change the notes on the existing subscription, if requested. Then change the terms and conditions, if requested. Then perform the remaining amendments based upon the effective dates specified. If multiple amendments have the same contract-effective dates, then execute adds before updates, and updates before removes. The update operation is atomic. If any of the updates fails, the entire operation is rolled back. The response of the Update Subscription call is based on the REST API minor version you set in the request header. The response structure might be different if you use different minor version numbers. If you have the Invoice Settlement feature enabled, we recommend that you set the zuora-version parameter to 207.0 or later. Otherwise, an error is returned. https://www.zuora.com/developer/api-reference/#operation/Object_PUTSubscription

type Token

type Token struct {
	AccessToken string `json:"access_token"`
	TokenType   string `json:"token_type"`
	ExpiresIn   int    `json:"expires_in"`
	Scope       string `json:"scope"`
	Jti         string `json:"jti"`
}

Token represents the OAuth token returned by Zuora.

type TokenService

type TokenService struct {
	// contains filtered or unexported fields
}

func (*TokenService) Token

func (t *TokenService) Token(ctx context.Context) (*Token, error)

Token Returns a token from TokenStore or from calling Zuora http endpoint. Possible return error BadRequest or InvalidResponse

type TokenStorer

type TokenStorer interface {
	Token() (bool, *Token)
	Update(*Token)
}

TokenStorer handles token renewal with two simple methods. Token() returns a boolean to indicate a token is valid and if valid, it will return the active token. Update() causes a side-effect to update a token in whichever backing store you choose.

type ZoqlComposer

type ZoqlComposer struct {
	Table     string
	Fields    []string
	Filter    QueryFilter
	OrFilter  []QueryFilter
	AndFilter []QueryFilter
}

ZoqlComposer helper struct to build a zoql query

func NewZoqlComposer

func NewZoqlComposer(table string, fields []string, zoqlComposerOption ...ZoqlComposerOption) *ZoqlComposer

NewZoqlComposer helper function to get a ready ZoqlComposer struct

func (*ZoqlComposer) Build

func (q *ZoqlComposer) Build() string

Build going away

func (*ZoqlComposer) String

func (q *ZoqlComposer) String() string

type ZoqlComposerOption

type ZoqlComposerOption func(*ZoqlComposer)

ZoqlComposerOption using functional options to construct a query

func QueryWithAndFilter

func QueryWithAndFilter(andFilter []QueryFilter) ZoqlComposerOption

QueryWithAndFilter adds an AND filter to final query

func QueryWithFilter

func QueryWithFilter(filter QueryFilter) ZoqlComposerOption

QueryWithFilter add a single filter to query

func QueryWithOrFilter

func QueryWithOrFilter(orFilter []QueryFilter) ZoqlComposerOption

QueryWithOrFilter adds an OR filter to query

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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