recurly

package module
v0.0.0-...-bd1588a Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2018 License: MIT Imports: 15 Imported by: 0

README

Recurly

Recurly is a Go (golang) API Client for the Recurly API.

Build Status GoDoc

Announcement: Credit Invoice Release

As of v2.10, Recurly has released data structure and API changes to support the credit invoice release. All sites created after May 8, 2018, have this turned on automatically. Existing sites must turn it on no later than Nov 1, 2018. New features will be applicable once the feature is turned on; legacy (existing) invoices will continue to use some deprecated features until they are closed. Most new code can coexist with existing, allowing you to write code to support your transition smoothly. Note that the new_dunning_event webhook data structure will change and both may be sent while you have both legacy and new invoices with dunning events. Please review the Parse and ParseDeprecated methods if you listen for this webhook. Deprecated code will be removed with any library updates no earlier than December 1, 2018.

References

Installation

Install using the "go get" command:

go get github.com/blacklightcms/recurly
Example
import "github.com/blacklightcms/recurly"

Construct a new Recurly Client and then work off of that. For example, to list accounts:

client := recurly.NewClient("subdomain", "apiKey", nil)
resp, accounts, err := client.Accounts.List(recurly.Params{"per_page": 20})

recurly.Response embeds http.Response and provides some convenience methods:

if resp.IsOK() {
    fmt.Println("Response was a 200-299 status code")
} else if resp.IsError() {
    fmt.Println("Response was NOT a 200-299 status code")

    // Loop through errors (422 status code only)
    for _, e := range resp.Errors {
        fmt.Printf("Message: %s; Field: %s; Symbol: %s\n", e.Message, e.Field, e.Symbol)
    }
}

if resp.IsClientError() {
    fmt.Println("You messed up. Response was a 400-499 status code")
} else if resp.IsServerError() {
    fmt.Println("Try again later. Response was a 500-599 status code")
}

// Get status code from http.response
if resp.StatusCode == 422 {
    // ...
}

Usage

The basic usage format is to create a client, and then operate directly off of each of the services.

The services are (each link to the GoDoc documentation):

Each of the services correspond to their respective sections in the Recurly API Documentation.

Here are a few examples:

Create Account
resp, a, err := client.Accounts.Create(recurly.Account{
    Code: "1",
    FirstName: "Verena",
    LastName: "Example",
    Email: "verena@example.com",
})

if resp.IsOK() {
    log.Printf("Account successfully created. Hosted Login Token: %s", a.HostedLoginToken)
}
Get Account
resp, a, err := client.Accounts.Get("1")
if resp.IsOK() {
    log.Printf("Account Found: %+v", a)
}
Get Accounts (pagination example)

All paginated methods (usually named List or List*) support a per_page and cursor parameter. Example usage:

resp, accounts, err := client.Accounts.List(recurly.Params{"per_page": 10})

if resp.IsError() {
    // Error occurred
}

for i, a := range accounts {
    // Loop through accounts
}

// Check for next page
next := resp.Next()
if next == "" {
    // No next page
}

// Retrieve next page
resp, accounts, err := client.Accounts.List(recurly.Params{
    "per_page": 10,
    "cursor": next,
})

// Check for prev page
prev := resp.Prev()
if prev == "" {
    // No prev page
}

// Retrieve prev page
resp, accounts, err := client.Accounts.List(recurly.Params{
    "per_page": 10,
    "cursor": prev,
})
Close account
resp, err := client.Accounts.Close("1")
Reopen account
resp, err := client.Accounts.Reopen("1")
Create Billing Info Using recurly.js Token
// 1 is the account code
resp, b, err := client.Billing.CreateWithToken("1", token)
Update Billing Info Using recurly.js Token
// 1 is the account code
resp, b, err := client.Billing.UpdateWithToken("1", token)
Create Billing with Credit Card
resp, b, err := client.Billing.Create("1", recurly.Billing{
    FirstName: "Verena",
    LastName:  "Example",
    Address:   "123 Main St.",
    City:      "San Francisco",
    State:     "CA",
    Zip:       "94105",
    Country:   "US",
    Number:    4111111111111111,
    Month:     10,
    Year:      2020,
})
Create Billing With Bank account
resp, b, err := client.Billing.Create("134", recurly.Billing{
    FirstName:     "Verena",
    LastName:      "Example",
    Address:       "123 Main St.",
    City:          "San Francisco",
    State:         "CA",
    Zip:           "94105",
    Country:       "US",
    NameOnAccount: "Acme, Inc",
    RoutingNumber: "123456780",
    AccountNumber: "111111111",
    AccountType:   "checking",
})
Creating Subscriptions

Subscriptions have different formats for creating and reading. Due to that, they have a special use case when creating -- a NewSubscription struct respectively. NewSubscription structs are only used for creating.

When updating a subscription, you should use the UpdateSubscription struct. All other creates/updates throughout use the same struct to create/update as to read.

// s will return a Subscription struct after creating using the
// NewSubscription struct.
resp, s, err := client.Subscriptions.Create(recurly.NewSubscription{
    PlanCode: "gold",
    Currency: "EUR",
    Account: recurly.Account{
        Code:      "b6f5783",
        Email:     "verena@example.com",
        FirstName: "Verena",
        LastName:  "Example",
        BillingInfo: &recurly.Billing{
            Number:            4111111111111111,
            Month:             12,
            Year:              2017,
            VerificationValue: 123,
            Address:           "400 Alabama St",
            City:              "San Francisco",
            State:             "CA",
            Zip:               "94110",
        },
    },
})

Working with Null* Types

This package has a few null types that ensure that zero values will marshal or unmarshal properly.

For example, booleans have a zero value of false in Go. If you need to explicitly send a false value, go will see that as a zero value and the omitempty option will ensure it doesn't get sent.

Likewise if you attempt to unmarshal empty/nil values into a struct, you will also get errors. The Null types help ensure things work as expected.

NullBool

NullBool is a basic struct that looks like this:

NullBool struct {
    Bool  bool
    Valid bool
}

The Valid field determines if the boolean value stored in Bool was intentionally set there, or if it should be discarded since the default will be false.

Here's how to work with NullBool:

// Create a new NullBool:
t := recurly.NewBool(true)

// Check if the value held in the bool is what you expected
fmt.Printf("%v", t.Is(true)) // true
fmt.Printf("%v", t.Is(false)) // false

If, however, NullBool looked like this:

recurly.NullBool{
    Bool: false,
    Valid: false,
}

Then those checks will always return false:

fmt.Printf("%v", t.Is(true)) // false
fmt.Printf("%v", t.Is(false)) // false
NullInt

NullInt works the same way as NullBool, but for integers.

i := recurly.NewInt(0)
i = recurly.NewInt(1)
i = recurly.NewInt(50)
NullTime

NullTime won't breakdown if an empty string / nil value is returned from the Recurly API. It also ensures times are always in UTC.

t := time.Now()
nt := recurly.NewTime(t) // time is now in UTC
fmt.Println(t.String()) // 2015-08-03T19:11:33Z

You can then use s.Account.Code to retrieve account info, or s.Invoice.Code to retrieve invoice info.

Transaction errors

In addition to the Errors property in the recurly.Response, response also contains a TransactionError field for Transaction Errors.

Be sure to check resp.TransactionError for any API calls that may return a transaction error for additional info. The TransactionError struct is defined like this:

TransactionError struct {
	XMLName          xml.Name `xml:"transaction_error"`
	ErrorCode        string   `xml:"error_code,omitempty"`
	ErrorCategory    string   `xml:"error_category,omitempty"`
	MerchantMessage  string   `xml:"merchant_message,omitempty"`
	CustomerMessage  string   `xml:"customer_message,omitempty"`
	GatewayErrorCode string   `xml:"gateway_error_code,omitempty"`
}

Link to transaction error documentation.

Using webhooks

Initial webhook support is in place. The following webhooks are supported:

Account Notifications

  • NewAccountNotification
  • UpdatedAccountNotification
  • CanceledAccountNotification
  • BillingInfoUpdatedNotification
  • BillingInfoUpdateFailedNotification

Subscription Notifications

  • NewSubscriptionNotification
  • UpdatedSubscriptionNotification
  • RenewedSubscriptionNotification
  • ExpiredSubscriptionNotification
  • CanceledSubscriptionNotification
  • PausedSubscriptionNotification
  • ResumedSubscriptionNotification
  • ScheduledSubscriptionPauseNotification
  • SubscriptionPauseModifiedNotification
  • PausedSubscriptionRenewalNotification
  • SubscriptionPauseCanceledNotification
  • ReactivatedAccountNotification

Invoice Notifications

  • NewInvoiceNotification
  • PastDueInvoiceNotification
  • ProcessingInvoiceNotification
  • ClosedInvoiceNotification

Payment Notifications

  • SuccessfulPaymentNotification
  • FailedPaymentNotification
  • VoidPaymentNotification
  • SuccessfulRefundNotification
  • ScheduledPaymentNotification
  • ProcessingPaymentNotification

Dunning Event Notifications

  • NewDunningEventNotification

Webhooks can be used by passing an io.Reader to webhooks.Parse, then using a switch statement with type assertions to determine the webhook returned.

PRs are welcome for additional webhooks.

License

recurly is available under the MIT License.

Documentation

Index

Constants

View Source
const (
	// AccountStateActive is the status for active accounts.
	AccountStateActive = "active"

	// AccountStateClosed is the status for closed accounts.
	AccountStateClosed = "closed"
)
View Source
const (
	AdjustmentStatePending = "pending"
	AdjustmentStateInvoied = "invoiced"
)

Adjustment state constants

View Source
const (
	CardTypeAmericanExpress    = "american_express"
	CardTypeDankort            = "dankort"
	CardTypeDinersClub         = "diners_club"
	CardTypeDiscover           = "discover"
	CardTypeForbrugsforeningen = "forbrugsforeningen"
	CardTypeJCB                = "jcb"
	CardTypeLaser              = "laser"
	CardTypeMaestro            = "maestro"
	CardTypeMaster             = "master"
	CardTypeVisa               = "visa"
)

Supported card type constants.

View Source
const (
	CreditPaymentActionPayment   = "payment" // applying the credit
	CreditPaymentActionGiftCard  = "gift_card"
	CreditPaymentActionRefund    = "refund"
	CreditPaymentActionReduction = "reduction" // reducing the amount of the credit without applying it
	CreditPaymentActionWriteOff  = "write_off" // used for voiding invoices
)

Credit payment action constants.

View Source
const (
	ChargeInvoiceStatePending    = "pending"    // previously "open"
	ChargeInvoiceStateProcessing = "processing" // ACH payments only
	ChargeInvoiceStatePastDue    = "past_due"
	ChargeInvoiceStatePaid       = "paid" // previously "collected"
	ChargeInvoiceStateFailed     = "failed"

	CreditInvoiceStateOpen       = "open"
	CreditInvoiceStateProcessing = "processing" // ACH/bank refund processing
	CreditInvoiceStateClosed     = "closed"
	CreditInvoiceStateVoided     = "voided"

	// Deprecated
	InvoiceStateOpenDeprecated      = "open"
	InvoiceStateCollectedDeprecated = "collected"
)

Invoice state constants. https://docs.recurly.com/docs/credit-invoices-release#section-invoice-attribute-changes

View Source
const (
	CollectionMethodAutomatic = "automatic" // card on file
	CollectionMethodManual    = "manual"    // external payment method
)

Collection method constants.

View Source
const (
	PaymentMethodCreditCard   = "credit_card"
	PaymentMethodPayPal       = "paypal"
	PaymentMethodEFT          = "eft"
	PaymentMethodWireTransfer = "wire_transfer"
	PaymentMethodMoneyOrder   = "money_order"
	PaymentMethodCheck        = "check"
	PaymentMethodOther        = "other"
)

Payment method constants.

View Source
const (
	ChargeInvoiceOriginPurchase        = "purchase"
	ChargeInvoiceOriginRenewal         = "renewal"
	ChargeInvoiceOriginImmediateChange = "immediate_change"
	ChargeInvoiceOriginTermination     = "termination"

	CreditInvoiceOriginGiftCard       = "gift_card"
	CreditInvoiceOriginRefund         = "refund"
	CreditInvoiceOriginCredit         = "credit"
	CreditInvoiceOriginWriteOff       = "write_off"
	CreditInvoiceOriginExternalCredit = "external_credit"
)

Invoice origin constants.

View Source
const (
	InvoiceTypeCharge = "charge"
	InvoiceTypeCredit = "credit"
	InvoiceTypeLegacy = "legacy" // all invoices prior to change have type legacy
)

Invoice type constants.

View Source
const (
	VoidRefundMethodTransactionFirst = "transaction_first"
	VoidRefundMethodCreditFirst      = "credit_first"
)

Refund constants.

View Source
const (
	RedemptionStateActive   = "active"
	RedemptionStateInactive = "inactive"
)
View Source
const (
	// SubscriptionStateActive represents subscriptions that are valid for the
	// current time. This includes subscriptions in a trial period
	SubscriptionStateActive = "active"

	// SubscriptionStateCanceled are subscriptions that are valid for
	// the current time but will not renew because a cancelation was requested
	SubscriptionStateCanceled = "canceled"

	// SubscriptionStateExpired are subscriptions that have expired and are no longer valid
	SubscriptionStateExpired = "expired"

	// SubscriptionStateFuture are subscriptions that will start in the
	// future, they are not active yet
	SubscriptionStateFuture = "future"

	// SubscriptionStateInTrial are subscriptions that are active or canceled
	// and are in a trial period
	SubscriptionStateInTrial = "in_trial"

	// SubscriptionStateLive are all subscriptions that are not expired
	SubscriptionStateLive = "live"

	// SubscriptionStatePastDue are subscriptions that are active or canceled
	// and have a past-due invoice
	SubscriptionStatePastDue = "past_due"

	// SubscriptionStatePaused are subscriptions that are in a paused state
	// and will not be billed for the set RemainingPauseCycles
	SubscriptionStatePaused = "paused"
)
View Source
const (
	// TransactionStatusSuccess is the status for a successful transaction.
	TransactionStatusSuccess = "success"

	// TransactionStatusFailed is the status for a failed transaction.
	TransactionStatusFailed = "failed"

	// TransactionStatusVoid is the status for a voided transaction.
	TransactionStatusVoid = "void"
)
View Source
const DateTimeFormat = "2006-01-02T15:04:05Z07:00"

DateTimeFormat is the format Recurly uses to represent datetimes.

Variables

This section is empty.

Functions

func SanitizeUUID

func SanitizeUUID(id string) string

SanitizeUUID returns the uuid without dashes.

Types

type AVSResult

type AVSResult struct {
	TransactionResult
}

AVSResult holds transaction results for address verification. http://developer.authorize.net/tools/errorgenerationguide/

type Account

type Account struct {
	XMLName               xml.Name           `xml:"account"`
	Code                  string             `xml:"account_code,omitempty"`
	State                 string             `xml:"state,omitempty"`
	Username              string             `xml:"username,omitempty"`
	Email                 string             `xml:"email,omitempty"`
	FirstName             string             `xml:"first_name,omitempty"`
	LastName              string             `xml:"last_name,omitempty"`
	CompanyName           string             `xml:"company_name,omitempty"`
	VATNumber             string             `xml:"vat_number,omitempty"`
	TaxExempt             NullBool           `xml:"tax_exempt,omitempty"`
	BillingInfo           *Billing           `xml:"billing_info,omitempty"`
	Address               Address            `xml:"address,omitempty"`
	AcceptLanguage        string             `xml:"accept_language,omitempty"`
	HostedLoginToken      string             `xml:"hosted_login_token,omitempty"`
	CreatedAt             NullTime           `xml:"created_at,omitempty"`
	HasPausedSubscription bool               `xml:"has_paused_subscription,omitempty"`
	ShippingAddresses     *[]ShippingAddress `xml:"shipping_addresses>shipping_address,omitempty"`
	CustomFields          *CustomFields      `xml:"custom_fields,omitempty"`
}

Account represents an individual account on your site

type AccountBalance

type AccountBalance struct {
	XMLName     xml.Name `xml:"account_balance"`
	AccountCode string   `xml:"-"`
	PastDue     bool     `xml:"past_due"`
	Balance     int      `xml:"balance_in_cents>USD"`
}

AccountBalance is used for getting the account balance.

type AccountsService

type AccountsService interface {
	List(params Params) (*Response, []Account, error)
	Get(code string) (*Response, *Account, error)
	LookupAccountBalance(code string) (*Response, *AccountBalance, error)
	Create(a Account) (*Response, *Account, error)
	Update(code string, a Account) (*Response, *Account, error)
	Close(code string) (*Response, error)
	Reopen(code string) (*Response, error)
	ListNotes(code string) (*Response, []Note, error)
}

AccountsService represents the interactions available for accounts.

type AddOn

type AddOn struct {
	XMLName                     xml.Name   `xml:"add_on"`
	Code                        string     `xml:"add_on_code,omitempty"`
	Name                        string     `xml:"name,omitempty"`
	DefaultQuantity             NullInt    `xml:"default_quantity,omitempty"`
	DisplayQuantityOnHostedPage NullBool   `xml:"display_quantity_on_hosted_page,omitempty"`
	TaxCode                     string     `xml:"tax_code,omitempty"`
	UnitAmountInCents           UnitAmount `xml:"unit_amount_in_cents,omitempty"`
	AccountingCode              string     `xml:"accounting_code,omitempty"`
	CreatedAt                   NullTime   `xml:"created_at,omitempty"`
}

AddOn represents an individual add on linked to a plan.

type AddOnsService

type AddOnsService interface {
	List(planCode string, params Params) (*Response, []AddOn, error)
	Get(planCode string, code string) (*Response, *AddOn, error)
	Create(planCode string, a AddOn) (*Response, *AddOn, error)
	Update(planCode string, code string, a AddOn) (*Response, *AddOn, error)
	Delete(planCode string, code string) (*Response, error)
}

AddOnsService represents the interactions available for add ons.

type Address

type Address struct {
	NameOnAccount string `xml:"name_on_account,omitempty"`
	FirstName     string `xml:"first_name,omitempty"`
	LastName      string `xml:"last_name,omitempty"`
	Company       string `xml:"company,omitempty"`
	Address       string `xml:"address1,omitempty"`
	Address2      string `xml:"address2,omitempty"`
	City          string `xml:"city,omitempty"`
	State         string `xml:"state,omitempty"`
	Zip           string `xml:"zip,omitempty"`
	Country       string `xml:"country,omitempty"`
	Phone         string `xml:"phone,omitempty"`
}

Address is used for embedded addresses within other structs.

func (Address) MarshalXML

func (a Address) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML ensures addresses marshal to nil if empty without the need to use pointers.

type Adjustment

type Adjustment struct {
	AccountCode            string
	InvoiceNumber          int
	SubscriptionUUID       string
	UUID                   string
	State                  string
	Description            string
	AccountingCode         string
	ProductCode            string
	Origin                 string
	UnitAmountInCents      int
	Quantity               int
	OriginalAdjustmentUUID string
	DiscountInCents        int
	TaxInCents             int
	TotalInCents           int
	Currency               string
	Taxable                NullBool
	TaxCode                string
	TaxType                string
	TaxRegion              string
	TaxRate                float64
	TaxExempt              NullBool
	TaxDetails             []TaxDetail
	StartDate              NullTime
	EndDate                NullTime
	CreatedAt              NullTime
	UpdatedAt              NullTime
}

Adjustment works with charges and credits on a given account.

func (Adjustment) MarshalXML

func (a Adjustment) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML marshals only the fields needed for creating/updating adjustments with the recurly API.

func (*Adjustment) UnmarshalXML

func (a *Adjustment) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML unmarshal a coupon redemption object. Minaly converts href links for coupons and accounts to CouponCode and AccountCodes.

type AdjustmentsService

type AdjustmentsService interface {
	List(accountCode string, params Params) (*Response, []Adjustment, error)
	Get(uuid string) (*Response, *Adjustment, error)
	Create(accountCode string, a Adjustment) (*Response, *Adjustment, error)
	Delete(uuid string) (*Response, error)
}

AdjustmentsService represents the interactions available for adjustments.

type Billing

type Billing struct {
	XMLName          xml.Name `xml:"billing_info,omitempty"`
	FirstName        string   `xml:"first_name,omitempty"`
	LastName         string   `xml:"last_name,omitempty"`
	Company          string   `xml:"company,omitempty"`
	Address          string   `xml:"address1,omitempty"`
	Address2         string   `xml:"address2,omitempty"`
	City             string   `xml:"city,omitempty"`
	State            string   `xml:"state,omitempty"`
	Zip              string   `xml:"zip,omitempty"`
	Country          string   `xml:"country,omitempty"`
	Phone            string   `xml:"phone,omitempty"`
	VATNumber        string   `xml:"vat_number,omitempty"`
	IPAddress        net.IP   `xml:"ip_address,omitempty"`
	IPAddressCountry string   `xml:"ip_address_country,omitempty"`

	// Credit Card Info
	FirstSix string `xml:"first_six,omitempty"` // String not int so card number can start with zero
	LastFour string `xml:"last_four,omitempty"` // String not int so that leading zeros are present
	CardType string `xml:"card_type,omitempty"`
	Number   int    `xml:"number,omitempty"`
	Month    int    `xml:"month,omitempty"`
	Year     int    `xml:"year,omitempty"`
	// VerificationValue is only used for create/update only. A Verification
	// Value will never be returned on read.
	VerificationValue int `xml:"verification_value,omitempty"`

	// Paypal
	PaypalAgreementID string `xml:"paypal_billing_agreement_id,omitempty"`

	// Amazon
	AmazonAgreementID string `xml:"amazon_billing_agreement_id,omitempty"`

	// Bank Account
	// Note: routing numbers and account numbers may start with zeros, so need
	// to treat them as strings
	NameOnAccount string `xml:"name_on_account,omitempty"`
	RoutingNumber string `xml:"routing_number,omitempty"`
	AccountNumber string `xml:"account_number,omitempty"`
	AccountType   string `xml:"account_type,omitempty"`

	// Token is used for create/update only. A token will never be returned
	// on read.
	Token string `xml:"token_id,omitempty"`
}

Billing represents billing info for a single account on your site

func (Billing) Type

func (b Billing) Type() string

Type returns the billing info type. Currently options: card, bank, ""

func (*Billing) UnmarshalXML

func (b *Billing) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML is a customer XML unmarshaler for billing info that supports unmarshaling null fields without errors.

type BillingService

type BillingService interface {
	Get(accountCode string) (*Response, *Billing, error)
	Create(accountCode string, b Billing) (*Response, *Billing, error)
	CreateWithToken(accountCode string, token string) (*Response, *Billing, error)
	Update(accountCode string, b Billing) (*Response, *Billing, error)
	UpdateWithToken(accountCode string, token string) (*Response, *Billing, error)
	Clear(accountCode string) (*Response, error)
}

BillingService represents the interactions available for billing.

type CVVResult

type CVVResult struct {
	TransactionResult
}

CVVResult holds transaction results for CVV fields. https://www.chasepaymentech.com/card_verification_codes.html

func (CVVResult) IsMatch

func (c CVVResult) IsMatch() bool

IsMatch returns true if the CVV code is a match.

func (CVVResult) IsNoMatch

func (c CVVResult) IsNoMatch() bool

IsNoMatch returns true if the CVV code did not match.

func (CVVResult) NotProcessed

func (c CVVResult) NotProcessed() bool

NotProcessed returns true if the CVV code was not processed.

func (CVVResult) ShouldHaveBeenPresent

func (c CVVResult) ShouldHaveBeenPresent() bool

ShouldHaveBeenPresent returns true if the CVV code should have been present on the card but was not indicated.

func (CVVResult) UnableToProcess

func (c CVVResult) UnableToProcess() bool

UnableToProcess returns true when the issuer was unable to process the CVV.

type Client

type Client struct {

	// BaseURL is the base url for api requests.
	BaseURL string

	// Services used for talking with different parts of the Recurly API
	Accounts          AccountsService
	Adjustments       AdjustmentsService
	Billing           BillingService
	Coupons           CouponsService
	Redemptions       RedemptionsService
	Invoices          InvoicesService
	Plans             PlansService
	AddOns            AddOnsService
	ShippingAddresses ShippingAddressesService
	Subscriptions     SubscriptionsService
	Transactions      TransactionsService
	CreditPayments    CreditPaymentsService
	Purchases         PurchasesService
	// contains filtered or unexported fields
}

Client manages communication with the Recurly API.

func NewClient

func NewClient(subDomain, apiKey string, httpClient *http.Client) *Client

NewClient returns a new instance of *Client. apiKey should be everything after "Basic ".

type Coupon

type Coupon struct {
	XMLName                  xml.Name    `xml:"coupon"`
	ID                       uint64      `xml:"id"`
	Code                     string      `xml:"coupon_code"`
	Type                     string      `xml:"coupon_type"`
	Name                     string      `xml:"name"`
	RedemptionResource       string      `xml:"redemption_resource"`
	State                    string      `xml:"state"`
	SingleUse                bool        `xml:"single_use"`
	AppliesToAllPlans        bool        `xml:"applies_to_all_plans"`
	Duration                 string      `xml:"duration"`
	DiscountType             string      `xml:"discount_type"`
	AppliesToNonPlanCharges  bool        `xml:"applies_to_non_plan_charges"`
	Description              string      `xml:"description,omitempty"`
	InvoiceDescription       string      `xml:"invoice_description,omitempty"`
	DiscountPercent          NullInt     `xml:"discount_percent,omitempty"`
	DiscountInCents          *UnitAmount `xml:"discount_in_cents,omitempty"`
	RedeemByDate             NullTime    `xml:"redeem_by_date,omitempty"`
	MaxRedemptions           NullInt     `xml:"max_redemptions,omitempty"`
	CreatedAt                NullTime    `xml:"created_at,omitempty"`
	UpdatedAt                NullTime    `xml:"updated_at,omitempty"`
	DeletedAt                NullTime    `xml:"deleted_at,omitempty"`
	TemporalUnit             string      `xml:"temporal_unit,omitempty"`
	TemporalAmount           NullInt     `xml:"temporal_amount,omitempty"`
	MaxRedemptionsPerAccount NullInt     `xml:"max_redemptions_per_account,omitempty"`
	UniqueCodeTemplate       string      `xml:"unique_code_template,omitempty"`
	UniqueCouponCodeCount    NullInt     `xml:"unique_coupon_codes_count,omitempty"`
	PlanCodes                []string    `xml:"plan_codes>plan_code,omitempty"`
}

Coupon represents an individual coupon on your site. https://dev.recurly.com/docs/lookup-a-coupon

type CouponsService

type CouponsService interface {
	List(params Params) (*Response, []Coupon, error)
	Get(code string) (*Response, *Coupon, error)
	Create(c Coupon) (*Response, *Coupon, error)
	Delete(code string) (*Response, error)
}

CouponsService represents the interactions available for coupons.

type CreditPayment

type CreditPayment struct {
	XMLName                   xml.Name `xml:"credit_payment"`
	AccountCode               string   `xml:"-"`
	UUID                      string   `xml:"uuid"`
	Action                    string   `xml:"action"`
	Currency                  string   `xml:"currency"`
	AmountInCents             int      `xml:"amount_in_cents"`
	OriginalInvoiceNumber     int      `xml:"-"`
	AppliedToInvoice          int      `xml:"-"`
	OriginalCreditPaymentUUID string   `xml:"-"`
	RefundTransactionUUID     string   `xml:"-"`
	CreatedAt                 NullTime `xml:"created_at"`
	UpdatedAt                 NullTime `xml:"updated_at,omitempty"`
	VoidedAt                  NullTime `xml:"voided_at,omitempty"`
}

CreditPayment is a credit that has been applied to an invoice. This is a read-only object. Unmarshaling an invoice is handled by the custom UnmarshalXML function.

func (*CreditPayment) UnmarshalXML

func (c *CreditPayment) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML unmarshals invoices and handles intermediary state during unmarshaling for types like href.

type CreditPaymentsService

type CreditPaymentsService interface {
	List(params Params) (*Response, []CreditPayment, error)
	ListAccount(accountCode string, params Params) (*Response, []CreditPayment, error)
	Get(uuid string) (*Response, *CreditPayment, error)
}

CreditPaymentsService represents the interactions available for credit payments.

type CustomFields

type CustomFields map[string]string

CustomFields represents custom key value pairs. Note that custom fields must be enabled on your Recurly site and must be added in the dashboard before they can be used.

func (CustomFields) MarshalXML

func (c CustomFields) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML marshals custom_fields.

func (*CustomFields) UnmarshalXML

func (c *CustomFields) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML unmarshals custom_fields.

type Error

type Error struct {
	XMLName     xml.Name `xml:"error"`
	Message     string   `xml:",innerxml"`
	Field       string   `xml:"field,attr"`
	Symbol      string   `xml:"symbol,attr"`
	Description string   `xml:"-"`
}

Error is an individual validation error

type Invoice

type Invoice struct {
	XMLName                 xml.Name        `xml:"invoice,omitempty"`
	AccountCode             string          `xml:"-"`
	Address                 Address         `xml:"-"`
	OriginalInvoiceNumber   int             `xml:"-"`
	UUID                    string          `xml:"-"`
	State                   string          `xml:"-"`
	InvoiceNumberPrefix     string          `xml:"-"`
	InvoiceNumber           int             `xml:"-"`
	PONumber                string          `xml:"po_number,omitempty"` // PostInvoice param
	VATNumber               string          `xml:"-"`
	DiscountInCents         int             `xml:"-"`
	SubtotalInCents         int             `xml:"-"`
	TaxInCents              int             `xml:"-"`
	TotalInCents            int             `xml:"-"`
	BalanceInCents          int             `xml:"-"`
	Currency                string          `xml:"-"`
	DueOn                   NullTime        `xml:"-"`
	CreatedAt               NullTime        `xml:"-"`
	UpdatedAt               NullTime        `xml:"-"`
	AttemptNextCollectionAt NullTime        `xml:"-"`
	ClosedAt                NullTime        `xml:"-"`
	Type                    string          `xml:"-"`
	Origin                  string          `xml:"-"`
	TaxType                 string          `xml:"-"`
	TaxRegion               string          `xml:"-"`
	TaxRate                 float64         `xml:"-"`
	NetTerms                NullInt         `xml:"net_terms,omitempty"`                // PostInvoice param
	CollectionMethod        string          `xml:"collection_method,omitempty"`        // PostInvoice param
	TermsAndConditions      string          `xml:"terms_and_conditions,omitempty"`     // PostInvoice param
	CustomerNotes           string          `xml:"customer_notes,omitempty"`           // PostInvoice param
	VatReverseChargeNotes   string          `xml:"vat_reverse_charge_notes,omitempty"` // PostInvoice param
	LineItems               []Adjustment    `xml:"-"`
	Transactions            []Transaction   `xml:"-"`
	CreditPayments          []CreditPayment `xml:"-"`
}

Invoice is an individual invoice for an account. The only fields annotated with XML tags are those for posting an invoice. Unmarshaling an invoice is handled by the custom UnmarshalXML function.

func (*Invoice) UnmarshalXML

func (i *Invoice) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML unmarshals invoices and handles intermediary state during unmarshaling for types like href.

type InvoiceCollection

type InvoiceCollection struct {
	XMLName       xml.Name `xml:"invoice_collection"`
	ChargeInvoice *Invoice `xml:"-"`
}

InvoiceCollection is the data type returned from Preview, Post, MarkFailed, and inside PreviewSubscription, and PreviewSubscriptionChange. In v2.12 this struct will include `credit_invoices`.

func (*InvoiceCollection) UnmarshalXML

func (i *InvoiceCollection) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML unmarshals invoices and handles intermediary state during unmarshaling for types like href.

type InvoicesService

type InvoicesService interface {
	List(params Params) (*Response, []Invoice, error)
	ListAccount(accountCode string, params Params) (*Response, []Invoice, error)
	Get(invoiceNumber int) (*Response, *Invoice, error)
	GetPDF(invoiceNumber int, language string) (*Response, *bytes.Buffer, error)
	Preview(accountCode string) (*Response, *Invoice, error)
	Create(accountCode string, invoice Invoice) (*Response, *Invoice, error)
	Collect(invoiceNumber int) (*Response, *Invoice, error)
	MarkPaid(invoiceNumber int) (*Response, *Invoice, error)
	MarkFailed(invoiceNumber int) (*Response, *Invoice, error)
	RefundVoidOpenAmount(invoiceNumber int, amountInCents int, refundMethod string) (*Response, *Invoice, error)
	VoidCreditInvoice(invoiceNumber int) (*Response, *Invoice, error)
	RecordPayment(offlinePayment OfflinePayment) (*Response, *Transaction, error)
}

InvoicesService represents the interactions available for invoices.

type NestedPlan

type NestedPlan struct {
	Code string `xml:"plan_code,omitempty"`
	Name string `xml:"name,omitempty"`
}

type NewSubscription

type NewSubscription struct {
	XMLName                 xml.Name             `xml:"subscription"`
	PlanCode                string               `xml:"plan_code"`
	Account                 Account              `xml:"account"`
	SubscriptionAddOns      *[]SubscriptionAddOn `xml:"subscription_add_ons>subscription_add_on,omitempty"`
	CouponCode              string               `xml:"coupon_code,omitempty"`
	UnitAmountInCents       int                  `xml:"unit_amount_in_cents,omitempty"`
	Currency                string               `xml:"currency"`
	Quantity                int                  `xml:"quantity,omitempty"`
	TrialEndsAt             NullTime             `xml:"trial_ends_at,omitempty"`
	StartsAt                NullTime             `xml:"starts_at,omitempty"`
	TotalBillingCycles      int                  `xml:"total_billing_cycles,omitempty"`
	RenewalBillingCycles    NullInt              `xml:"renewal_billing_cycles"`
	FirstRenewalDate        NullTime             `xml:"first_renewal_date,omitempty"` // Deprecated, use NextBillDate
	NextBillDate            NullTime             `xml:"next_bill_date,omitempty"`
	CollectionMethod        string               `xml:"collection_method,omitempty"`
	AutoRenew               bool                 `xml:"auto_renew,omitempty"`
	NetTerms                NullInt              `xml:"net_terms,omitempty"`
	PONumber                string               `xml:"po_number,omitempty"`
	Bulk                    bool                 `xml:"bulk,omitempty"`
	TermsAndConditions      string               `xml:"terms_and_conditions,omitempty"`
	CustomerNotes           string               `xml:"customer_notes,omitempty"`
	VATReverseChargeNotes   string               `xml:"vat_reverse_charge_notes,omitempty"`
	BankAccountAuthorizedAt NullTime             `xml:"bank_account_authorized_at,omitempty"`
	CustomFields            *CustomFields        `xml:"custom_fields,omitempty"`
}

NewSubscription is used to create new subscriptions.

type NewSubscriptionResponse

type NewSubscriptionResponse struct {
	Subscription *Subscription
	Transaction  *Transaction // UnprocessableEntity errors return only the transaction
}

NewSubscriptionResponse is used to unmarshal either the subscription or the transaction.

type Note

type Note struct {
	XMLName   xml.Name  `xml:"note"`
	Message   string    `xml:"message,omitempty"`
	CreatedAt time.Time `xml:"created_at,omitempty"`
}

Note holds account notes.

type NullBool

type NullBool struct {
	Bool  bool
	Valid bool
}

NullBool is used for properly handling bool types with the Recurly API. Without it, setting a false boolean value will be ignored when encoding xml requests to the Recurly API.

func NewBool

func NewBool(b bool) NullBool

NewBool creates a new NullBool.

func (NullBool) Is

func (n NullBool) Is(b bool) bool

Is checks to see if the boolean is valid and equivalent

func (NullBool) MarshalJSON

func (n NullBool) MarshalJSON() ([]byte, error)

MarshalJSON marshals an bool based on whether valid is true

func (NullBool) MarshalXML

func (n NullBool) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML marshals NullBools to XML. Otherwise nothing is marshaled.

func (*NullBool) UnmarshalXML

func (n *NullBool) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML unmarshals an bool properly, as well as marshaling an empty string to nil.

type NullInt

type NullInt struct {
	Int   int
	Valid bool
}

NullInt is used for properly handling int types that could be null.

func NewInt

func NewInt(i int) NullInt

NewInt builds a new NullInt struct.

func (NullInt) MarshalJSON

func (n NullInt) MarshalJSON() ([]byte, error)

MarshalJSON marshals an int based on whether valid is true

func (NullInt) MarshalXML

func (n NullInt) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML marshals NullInts greater than zero to XML. Otherwise nothing is marshaled.

func (*NullInt) UnmarshalXML

func (n *NullInt) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML unmarshals an int properly, as well as marshaling an empty string to nil.

type NullMarshal

type NullMarshal struct{}

NullMarshal can be embedded in structs that are read-only or just should never be marshaled

func (NullMarshal) MarshalXML

func (nm NullMarshal) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML ensures that nullMarshal doesn't marshal any xml.

type NullTime

type NullTime struct {
	*time.Time
	Raw string `xml:",innerxml"`
}

NullTime is used for properly handling time.Time types that could be null.

func NewTime

func NewTime(t time.Time) NullTime

NewTime generates a new NullTime.

func NewTimeFromString

func NewTimeFromString(str string) NullTime

NewTimeFromString generates a new NullTime based on a time string in the DateTimeFormat format. This is primarily used in unit testing.

func (NullTime) MarshalJSON

func (t NullTime) MarshalJSON() ([]byte, error)

MarshalJSON method has to be added here due to embeded interface json marshal issue in Go with panic on nil time field

func (NullTime) MarshalXML

func (t NullTime) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML marshals times into their proper format. Otherwise nothing is marshaled. All times are sent in UTC.

func (NullTime) String

func (t NullTime) String() string

String returns a string representation of the time in UTC using the DateTimeFormat constant as the format.

func (*NullTime) UnmarshalXML

func (t *NullTime) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML unmarshals an int properly, as well as marshaling an empty string to nil.

type OfflinePayment

type OfflinePayment struct {
	XMLName       xml.Name   `xml:"transaction"`
	InvoiceNumber int        `xml:"-"`
	PaymentMethod string     `xml:"payment_method"`
	CollectedAt   *time.Time `xml:"collected_at,omitempty"`
	Amount        int        `xml:"amount_in_cents,omitempty"`
	Description   string     `xml:"description,omitempty"`
}

OfflinePayment is a payment received outside the system to be recorded in Recurly.

type Params

type Params map[string]interface{}

Params are used to send parameters with the request.

type PendingSubscription

type PendingSubscription struct {
	XMLName            xml.Name            `xml:"pending_subscription"`
	Plan               NestedPlan          `xml:"plan,omitempty"`
	UnitAmountInCents  int                 `xml:"unit_amount_in_cents,omitempty"`
	Quantity           int                 `xml:"quantity,omitempty"` // Quantity of subscriptions
	SubscriptionAddOns []SubscriptionAddOn `xml:"subscription_add_ons>subscription_add_on,omitempty"`
}

PendingSubscription are updates to the subscription or subscription add ons that will be made on the next renewal.

type Plan

type Plan struct {
	XMLName                  xml.Name   `xml:"plan"`
	Code                     string     `xml:"plan_code,omitempty"`
	Name                     string     `xml:"name"`
	Description              string     `xml:"description,omitempty"`
	SuccessURL               string     `xml:"success_url,omitempty"`
	CancelURL                string     `xml:"cancel_url,omitempty"`
	DisplayDonationAmounts   NullBool   `xml:"display_donation_amounts,omitempty"`
	DisplayQuantity          NullBool   `xml:"display_quantity,omitempty"`
	DisplayPhoneNumber       NullBool   `xml:"display_phone_number,omitempty"`
	BypassHostedConfirmation NullBool   `xml:"bypass_hosted_confirmation,omitempty"`
	UnitName                 string     `xml:"unit_name,omitempty"`
	PaymentPageTOSLink       string     `xml:"payment_page_tos_link,omitempty"`
	IntervalUnit             string     `xml:"plan_interval_unit,omitempty"`
	IntervalLength           int        `xml:"plan_interval_length,omitempty"`
	TrialIntervalUnit        string     `xml:"trial_interval_unit,omitempty"`
	TrialIntervalLength      int        `xml:"trial_interval_length,omitempty"`
	TotalBillingCycles       NullInt    `xml:"total_billing_cycles,omitempty"`
	AccountingCode           string     `xml:"accounting_code,omitempty"`
	CreatedAt                NullTime   `xml:"created_at,omitempty"`
	TaxExempt                NullBool   `xml:"tax_exempt,omitempty"`
	TaxCode                  string     `xml:"tax_code,omitempty"`
	AutoRenew                bool       `xml:"auto_renew,omitempty"`
	UnitAmountInCents        UnitAmount `xml:"unit_amount_in_cents"`
	SetupFeeInCents          UnitAmount `xml:"setup_fee_in_cents,omitempty"`
}

Plan represents an individual plan on your site.

type PlansService

type PlansService interface {
	List(params Params) (*Response, []Plan, error)
	Get(code string) (*Response, *Plan, error)
	Create(p Plan) (*Response, *Plan, error)
	Update(code string, p Plan) (*Response, *Plan, error)
	Delete(code string) (*Response, error)
}

PlansService represents the interactions available for plans.

type Purchase

type Purchase struct {
	XMLName               xml.Name          `xml:"purchase"`
	Account               Account           `xml:"account,omitempty"`
	Adjustments           []Adjustment      `xml:"adjustments>adjustment,omitempty"`
	CollectionMethod      string            `xml:"collection_method,omitempty"`
	Currency              string            `xml:"currency"`
	PONumber              string            `xml:"po_number,omitempty"`
	NetTerms              NullInt           `xml:"net_terms,omitempty"`
	GiftCard              string            `xml:"gift_card>redemption_code,omitempty"`
	CouponCodes           []string          `xml:"coupon_codes>coupon_code,omitempty"`
	Subscriptions         []NewSubscription `xml:"subscriptions>subscription,omitempty"`
	CustomerNotes         string            `xml:"customer_notes,omitempty"`
	TermsAndConditions    string            `xml:"terms_and_conditions,omitempty"`
	VATReverseChargeNotes string            `xml:"vat_reverse_charge_notes,omitempty"`
	ShippingAddressID     int64             `xml:"shipping_address_id,omitempty"`
}

Purchase represents an individual checkout holding at least one subscription OR one adjustment

type PurchasesService

type PurchasesService interface {
	Create(p Purchase) (*Response, *InvoiceCollection, error)
	Preview(p Purchase) (*Response, *InvoiceCollection, error)
}

PurchasesService represents the interactions available for a purchase involving at least one adjustment or one subscription.

type Redemption

type Redemption struct {
	UUID                   string
	SubscriptionUUID       string
	AccountCode            string
	CouponCode             string
	SingleUse              bool
	TotalDiscountedInCents int
	Currency               string
	State                  string
	CreatedAt              NullTime
	UpdatedAt              NullTime
}

Redemption holds redeemed coupons for an account or invoice.

func (*Redemption) UnmarshalXML

func (r *Redemption) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML unmarshal a coupon redemption object. Minaly converts href links for coupons and accounts to CouponCode and AccountCodes.

type RedemptionsService

type RedemptionsService interface {
	GetForAccount(accountCode string) (*Response, []Redemption, error)
	GetForInvoice(invoiceNumber string) (*Response, []Redemption, error)
	Redeem(code string, accountCode string, currency string) (*Response, *Redemption, error)
	RedeemToSubscription(code string, accountCode string, currency string, subscriptionUUID string) (*Response, *Redemption, error)
	Delete(accountCode string) (*Response, error)
}

RedemptionsService represents the interactions available for redemptions.

type Response

type Response struct {
	*http.Response

	// Errors holds an array of validation errors if any occurred.
	Errors []Error
	// contains filtered or unexported fields
}

Response is returned for each API call.

func (*Response) IsClientError

func (r *Response) IsClientError() bool

IsClientError returns true if the request resulted in a 400-499 status code.

func (*Response) IsError

func (r *Response) IsError() bool

IsError returns true if the request was not successful.

func (*Response) IsOK

func (r *Response) IsOK() bool

IsOK returns true if the request was successful.

func (*Response) IsServerError

func (r *Response) IsServerError() bool

IsServerError returns true if the request resulted in a 500-599 status code -- indicating you may want to retry the request later.

func (*Response) Next

func (r *Response) Next() string

Next returns the cursor for the next page of paginated results. If no next page exists, an empty string is returned.

func (*Response) Prev

func (r *Response) Prev() string

Prev returns the cursor for the previous page of paginated results. If no previous page exists, an empty string is returned.

type ShippingAddress

type ShippingAddress struct {
	XMLName     xml.Name `xml:"shipping_address"`
	AccountCode string   `xml:"account,omitempty"`
	ID          int64    `xml:"id,omitempty"`
	FirstName   string   `xml:"first_name"`
	LastName    string   `xml:"last_name"`
	Nickname    string   `xml:"nickname,omitempty"`
	Address     string   `xml:"address1"`
	Address2    string   `xml:"address2"`
	Company     string   `xml:"company,omitempty"`
	City        string   `xml:"city"`
	State       string   `xml:"state"`
	Zip         string   `xml:"zip"`
	Country     string   `xml:"country"`
	Phone       string   `xml:"phone,omitempty"`
	Email       string   `xml:"email,omitempty"`
	VATNumber   string   `xml:"vat_number,omitempty"`
	CreatedAt   NullTime `xml:"created_at,omitempty"`
	UpdatedAt   NullTime `xml:"updated_at,omitempty"`
}

ShippingAddress represents a shipping address

func (*ShippingAddress) UnmarshalXML

func (s *ShippingAddress) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML unmarshals shipping addresses and handles intermediary state during unmarshaling for types like href.

type ShippingAddressesService

type ShippingAddressesService interface {
	ListAccount(accountCode string, params Params) (*Response, []ShippingAddress, error)
	Create(accountCode string, address ShippingAddress) (*Response, *ShippingAddress, error)
	Update(accountCode string, shippingAddressID int64, address ShippingAddress) (*Response, *ShippingAddress, error)
	Delete(accountCode string, shippingAddressID int64) (*Response, error)
	GetSubscriptions(accountCode string, shippingAddressID int64) (*Response, []Subscription, error)
}

ShippingAddressesService represents the interactions available for shipping addresses.

type Subscription

type Subscription struct {
	XMLName                xml.Name             `xml:"subscription"`
	Plan                   NestedPlan           `xml:"plan,omitempty"`
	AccountCode            string               `xml:"-"`
	InvoiceNumber          int                  `xml:"-"`
	UUID                   string               `xml:"uuid,omitempty"`
	State                  string               `xml:"state,omitempty"`
	UnitAmountInCents      int                  `xml:"unit_amount_in_cents,omitempty"`
	Currency               string               `xml:"currency,omitempty"`
	Quantity               int                  `xml:"quantity,omitempty"`
	TotalAmountInCents     int                  `xml:"total_amount_in_cents,omitempty"`
	ActivatedAt            NullTime             `xml:"activated_at,omitempty"`
	CanceledAt             NullTime             `xml:"canceled_at,omitempty"`
	ExpiresAt              NullTime             `xml:"expires_at,omitempty"`
	CurrentPeriodStartedAt NullTime             `xml:"current_period_started_at,omitempty"`
	CurrentPeriodEndsAt    NullTime             `xml:"current_period_ends_at,omitempty"`
	TrialStartedAt         NullTime             `xml:"trial_started_at,omitempty"`
	TrialEndsAt            NullTime             `xml:"trial_ends_at,omitempty"`
	PausedAt               NullTime             `xml:"paused_at,omitempty"`
	ResumeAt               NullTime             `xml:"resume_at,omitempty"`
	TaxInCents             int                  `xml:"tax_in_cents,omitempty"`
	TaxType                string               `xml:"tax_type,omitempty"`
	TaxRegion              string               `xml:"tax_region,omitempty"`
	TaxRate                float64              `xml:"tax_rate,omitempty"`
	PONumber               string               `xml:"po_number,omitempty"`
	NetTerms               NullInt              `xml:"net_terms,omitempty"`
	SubscriptionAddOns     []SubscriptionAddOn  `xml:"subscription_add_ons>subscription_add_on,omitempty"`
	CurrentTermStartedAt   NullTime             `xml:"current_term_started_at,omitempty"`
	CurrentTermEndsAt      NullTime             `xml:"current_term_ends_at,omitempty"`
	PendingSubscription    *PendingSubscription `xml:"pending_subscription,omitempty"`
	InvoiceCollection      *InvoiceCollection   `xml:"invoice_collection,omitempty"`
	RemainingPauseCycles   int                  `xml:"remaining_pause_cycles,omitempty"`
	CollectionMethod       string               `xml:"collection_method"`
	CustomerNotes          string               `xml:"customer_notes,omitempty"`
	AutoRenew              bool                 `xml:"auto_renew,omitempty"`
	RenewalBillingCycles   NullInt              `xml:"renewal_billing_cycles"`
	CustomFields           *CustomFields        `xml:"custom_fields,omitempty"`
}

Subscription represents an individual subscription.

func (Subscription) MakeUpdate

func (s Subscription) MakeUpdate() UpdateSubscription

MakeUpdate creates an UpdateSubscription with values that need to be passed on update to be retained (meaning nil/zero values will delete that value). After calling MakeUpdate you should modify the struct with your updates. Once you're ready you can call client.Subscriptions.Update

func (*Subscription) UnmarshalXML

func (s *Subscription) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML unmarshals transactions and handles intermediary state during unmarshaling for types like href.

type SubscriptionAddOn

type SubscriptionAddOn struct {
	XMLName           xml.Name `xml:"subscription_add_on"`
	Type              string   `xml:"add_on_type,omitempty"`
	Code              string   `xml:"add_on_code"`
	UnitAmountInCents NullInt  `xml:"unit_amount_in_cents,omitempty"`
	Quantity          int      `xml:"quantity,omitempty"`
}

SubscriptionAddOn are add ons to subscriptions. https://docs.com/api/subscriptions/subscription-add-ons

type SubscriptionNotes

type SubscriptionNotes struct {
	XMLName               xml.Name `xml:"subscription"`
	TermsAndConditions    string   `xml:"terms_and_conditions,omitempty"`
	CustomerNotes         string   `xml:"customer_notes,omitempty"`
	VATReverseChargeNotes string   `xml:"vat_reverse_charge_notes,omitempty"`
}

SubscriptionNotes is used to update a subscription's notes.

type SubscriptionsService

type SubscriptionsService interface {
	List(params Params) (*Response, []Subscription, error)
	ListAccount(accountCode string, params Params) (*Response, []Subscription, error)
	Get(uuid string) (*Response, *Subscription, error)
	Create(sub NewSubscription) (*Response, *NewSubscriptionResponse, error)
	Preview(sub NewSubscription) (*Response, *Subscription, error)
	Update(uuid string, sub UpdateSubscription) (*Response, *Subscription, error)
	UpdateNotes(uuid string, n SubscriptionNotes) (*Response, *Subscription, error)
	PreviewChange(uuid string, sub UpdateSubscription) (*Response, *Subscription, error)
	Cancel(uuid string) (*Response, *Subscription, error)
	Reactivate(uuid string) (*Response, *Subscription, error)
	TerminateWithPartialRefund(uuid string) (*Response, *Subscription, error)
	TerminateWithFullRefund(uuid string) (*Response, *Subscription, error)
	TerminateWithoutRefund(uuid string) (*Response, *Subscription, error)
	Postpone(uuid string, dt time.Time, bulk bool) (*Response, *Subscription, error)
	Pause(uuid string, cycles int) (*Response, *Subscription, error)
	Resume(uuid string) (*Response, *Subscription, error)
}

SubscriptionsService represents the interactions available for subscriptions.

type TaxDetail

type TaxDetail struct {
	XMLName    xml.Name `xml:"tax_detail"`
	Name       string   `xml:"name,omitempty"`
	Type       string   `xml:"type,omitempty"`
	TaxRate    float64  `xml:"tax_rate,omitempty"`
	TaxInCents int      `xml:"tax_in_cents,omitempty"`
}

TaxDetail holds tax information and is embedded in an Adjustment. TaxDetails are a read only field, so theys houldn't marshall

type Transaction

type Transaction struct {
	InvoiceNumber    int               // Read only
	UUID             string            `xml:"uuid,omitempty"` // Read only
	Action           string            `xml:"action,omitempty"`
	AmountInCents    int               `xml:"amount_in_cents"`
	TaxInCents       int               `xml:"tax_in_cents,omitempty"`
	Currency         string            `xml:"currency"`
	Status           string            `xml:"status,omitempty"`
	Description      string            `xml:"description,omitempty"`
	ProductCode      string            `xml:"-"` // Write only field, is saved on the invoice line item but not the transaction
	PaymentMethod    string            `xml:"payment_method,omitempty"`
	Reference        string            `xml:"reference,omitempty"`
	Source           string            `xml:"source,omitempty"`
	Recurring        NullBool          `xml:"recurring,omitempty"`
	Test             bool              `xml:"test,omitempty"`
	Voidable         NullBool          `xml:"voidable,omitempty"`
	Refundable       NullBool          `xml:"refundable,omitempty"`
	IPAddress        net.IP            `xml:"ip_address,omitempty"`
	TransactionError *TransactionError `xml:"transaction_error,omitempty"` // Read only
	CVVResult        CVVResult         `xml:"cvv_result"`                  // Read only
	AVSResult        AVSResult         `xml:"avs_result"`                  // Read only
	AVSResultStreet  string            `xml:"avs_result_street,omitempty"` // Read only
	AVSResultPostal  string            `xml:"avs_result_postal,omitempty"` // Read only
	CreatedAt        NullTime          `xml:"created_at,omitempty"`        // Read only
	Account          Account           `xml:"details>account"`             // Read only
}

Transaction represents an individual transaction.

func (Transaction) MarshalXML

func (t Transaction) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML marshals a transaction sending only the fields recurly allows for writes. Read only fields are not encoded, and account is written as <account></account> instead of as <details><account></account></details> (like it is in Transaction).

func (*Transaction) UnmarshalXML

func (t *Transaction) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML unmarshals transactions and handles intermediary state during unmarshaling for types like href.

type TransactionError

type TransactionError struct {
	XMLName          xml.Name `xml:"transaction_error"`
	ErrorCode        string   `xml:"error_code,omitempty"`
	ErrorCategory    string   `xml:"error_category,omitempty"`
	MerchantMessage  string   `xml:"merchant_message,omitempty"`
	CustomerMessage  string   `xml:"customer_message,omitempty"`
	GatewayErrorCode string   `xml:"gateway_error_code,omitempty"`
}

TransactionError is an error encounted from your payment gateway that recurly has standardized. https://recurly.readme.io/v2.0/page/transaction-errors

type TransactionResult

type TransactionResult struct {
	NullMarshal
	Code    string `xml:"code,attr"`
	Message string `xml:",innerxml"`
}

TransactionResult is included in CVV results.

type Transactions

type Transactions []Transaction

Transactions is a sortable slice of Transaction. It implements sort.Interface.

func (Transactions) Len

func (s Transactions) Len() int

func (Transactions) Less

func (s Transactions) Less(i, j int) bool

func (Transactions) Swap

func (s Transactions) Swap(i, j int)

type TransactionsService

type TransactionsService interface {
	List(params Params) (*Response, []Transaction, error)
	ListAccount(accountCode string, params Params) (*Response, []Transaction, error)
	Get(uuid string) (*Response, *Transaction, error)
	Create(t Transaction) (*Response, *Transaction, error)
}

TransactionsService represents the interactions available for transactions.

type UnitAmount

type UnitAmount struct {
	USD int `xml:"USD,omitempty"`
	EUR int `xml:"EUR,omitempty"`
	GBP int `xml:"GBP,omitempty"`
	CAD int `xml:"CAD,omitempty"`
	AUD int `xml:"AUD,omitempty"`
}

UnitAmount is used in plans where unit amounts are represented in cents in both EUR and USD.

func (UnitAmount) MarshalXML

func (u UnitAmount) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML marshals NullBools to XML. Otherwise nothing is marshaled.

func (*UnitAmount) UnmarshalXML

func (u *UnitAmount) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML unmarshals an int properly, as well as marshaling an empty string to nil.

type UpdateSubscription

type UpdateSubscription struct {
	XMLName              xml.Name             `xml:"subscription"`
	Timeframe            string               `xml:"timeframe,omitempty"`
	PlanCode             string               `xml:"plan_code,omitempty"`
	Quantity             int                  `xml:"quantity,omitempty"`
	UnitAmountInCents    int                  `xml:"unit_amount_in_cents,omitempty"`
	RenewalBillingCycles NullInt              `xml:"renewal_billing_cycles"`
	CollectionMethod     string               `xml:"collection_method,omitempty"`
	AutoRenew            bool                 `xml:"auto_renew,omitempty"`
	NetTerms             NullInt              `xml:"net_terms,omitempty"`
	PONumber             string               `xml:"po_number,omitempty"`
	SubscriptionAddOns   *[]SubscriptionAddOn `xml:"subscription_add_ons>subscription_add_on,omitempty"`
}

UpdateSubscription is used to update subscriptions

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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