chargebee

package module
v2.1.9-patched.1+incom... Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2021 License: MIT Imports: 59 Imported by: 0

README

Chargebee Go Client Library - API V2

This is the beta version of Go Library for integrating with Chargebee. Sign up for a Chargebee account here.

Installation

Install the latest version of the library with the following commands:

	go get github.com/chargebee/chargebee-go

Go Requirement

Use go1.3 or newer.

Usage

To create a customer & subscription
import (
  "fmt"
  "github.com/chargebee/chargebee-go"
  subscriptionAction "github.com/chargebee/chargebee-go/actions/subscription"
  "github.com/chargebee/chargebee-go/models/subscription"
)

func main() {
  chargebee.Configure("{site}", "{site_api_key}")
  res, err := subscriptionAction.Create(&subscription.CreateRequestParams{
    PlanId:         "cbdemo_grow",
    BillingCycles:  chargebee.Int32(3),
    AutoCollection: enum.AutoCollectionOff,
    Customer: &subscription.CreateCustomerParams{
      Email:          "john@user.com",
      FirstName:      "John",
      LastName:       "Doe",
      Locale:         "fr-CA",
      Phone:          "+1-949-999-9999",
      AutoCollection: enum.AutoCollectionOff,
    }}).Request()
  if err != nil {
    panic(err)
  }else{
     Subscription := res.Subscription
     Customer := res.Customer
     Invoice := res.Invoice
  }
}
To create a subscription with addons, metadata, coupons :
import (
  "fmt"
  "github.com/chargebee/chargebee-go"
  subscriptionAction "github.com/chargebee/chargebee-go/actions/subscription"
  "github.com/chargebee/chargebee-go/models/subscription"
)

func main() {
  chargebee.Configure("{site}", "{site_api_key}")
  res, err := subscriptionAction.Create(&subscription.CreateRequestParams{
    PlanId:         "cbdemo_grow",
    BillingCycles:  chargebee.Int32(3),
    AutoCollection: enum.AutoCollectionOff,
    Customer: &subscription.CreateCustomerParams{
      Email:          "john@user.com",
      FirstName:      "John",
      LastName:       "Doe",
      Locale:         "fr-CA",
      Phone:          "+1-949-999-9999",
      AutoCollection: enum.AutoCollectionOff,
    },
    BillingAddress: &subscription.CreateBillingAddressParams{
      FirstName: "John",
      LastName:  "Doe",
      Line1:     "PO Box 9999",
      City:      "Walnut",
      State:     "California",
      Zip:       "91789",
      Country:   "US",
    },
    MetaData: map[string]interface{}{
      "features": map[string]interface{}{
        "usage-limit":        "5GB",
        "speed-within-quota": "2MBbps",
        "post-usage-quota":   "512kbps",
      },
    },
    Addons: []*subscription.CreateAddonParams{
      {
        Id: "cbdemo_conciergesupport",
      },
      {
        Id:       "cbdemo_additionaluser",
        Quantity: chargebee.Int32(2),
      },
    },
    CouponIds: []string{"cbdemo_earlybird"},
  }).Request()
  if err != nil {
    panic(err)
  }else{
  Subscription := res.Subscription
  Customer := res.Customer
  Card := res.Card
  Invoice := res.Invoice
  UnbilledCharges := res.UnbilledCharges
  }
}
Use of Filters In List API

To retrieve list of subscriptions :

import (
  "fmt"
  "github.com/chargebee/chargebee-go"
  subscriptionAction "github.com/chargebee/chargebee-go/actions/subscription"
  "github.com/chargebee/chargebee-go/filter"
  "github.com/chargebee/chargebee-go/models/subscription"
)

func main() {
  chargebee.Configure("{site}", "{site_api_key}")
  res, err := subscriptionAction.List(&subscription.ListRequestParams{
    Limit: chargebee.Int32(5),
    Id: &filter.StringFilter{
      In: []string{"cbdemo_john-sub", "cbdemo_ricky-sub"},
    },
    PlanId: &filter.StringFilter{
      IsNot: "basic",
    },
    Status: &filter.EnumFilter{
      Is: subscriptionEnum.StatusActive,
    },
    SortBy: &filter.SortFilter{
      Asc: "created_at",
    },
  }).ListRequest()
  if err != nil {
    panic(err)
  }else{
  for i := range res.List {
    Subscription := res.List[i].Subscription
    Customer := res.List[i].Customer
    Card := res.List[i].Card
  }
  }
}
To create subscription with custom headers and custom fields:
import (
  "fmt"
  "github.com/chargebee/chargebee-go"
  subscriptionAction "github.com/chargebee/chargebee-go/actions/subscription"
  "github.com/chargebee/chargebee-go/models/subscription"
)

func main() {
  chargebee.Configure("{site}", "{site_api_key}")
  res, err := subscriptionAction.Create(&subscription.CreateRequestParams{
    PlanId: "cbdemo_grow",
  }).Headers("chargebee-request-origin-ip", "192.168.1.2").AddParams("customer[cf_gender]","Female").Request() // Customer level custom field. 
  if err != nil {
    panic(err)
  }else{
  Subscription := res.Subscription
  Customer := res.Customer
  Card := res.Card
  Invoice := res.Invoice
  UnbilledCharges := res.UnbilledCharges
  }
}

Test suite needs testify's require package to run :

  go get github.com/stretchr/testify/require

Error Handling

_,err := //Go Library call 

if err != nil {
  if goErr,ok := err.(*chargebee.Error); ok {

    //Identify the type of Error 
    switch goErr.Type {
      
    case chargebee.PaymentError:
      // First check for card parameters entered by the user.
        // We recommend you to validate the input at the client side itself to catch simple mistakes.
        if goErr.Param == "card[number]" {
          // Ask your user to recheck the card number. A better way is to use 
          // Stripe's https://github.com/stripe/jquery.payment for validating it in the client side itself.  
          //}else if(goErr.Param == <other card params>){ 
            //Similarly check for other card parameters entered by the user.
            //....
        } else {
            // Verfication or processing failures.
            // Provide a standard message to your user to recheck his card details or provide a different card.
            // Like  'Sorry,there was a problem when processing your card, please check the details and try again'. 
        }

      case chargebee.InvalidRequestError:
        // For coupons you could decide to provide specific messages by using 
        // the 'api_error_code' attribute in the ex.
        if goErr.Param == "coupon" {
          if goErr.APIErrorCode == "resource_not_found" {
            // Inform user to recheck his coupon code.
          } else if goErr.APIErrorCode == "resource_limit_exhausted" {
            // Inform user that the coupon code has expired.
          } else if goErr.APIErrorCode == "invalid_request" {
            // Inform user that the coupon code is not applicable for his plan(/addons).
          } else {
            // Inform user to recheck his coupon code.
          }
        } else {
          // Since you would have validated all other parameters on your side itself, 
          // this could probably be a bug in your code. Provide a generic message to your users.
        }

    case chargebee.OperationFailedError:
      // Indicates that the request parameters were right but the request couldn't be completed.
        // The reasons might be "api_request_limit_exceeded" or could be due to an issue in ChargeBee side.
        // These should occur very rarely and mostly be of temporary nature. 
        // You could ask your user to retry after some time.
      default :
        // These are unhandled exceptions (Could be due to a bug in your code or very rarely in client library).
          // The errors from ChargeBee such as authentication failures will come here.
            // You could ask users contact your support.     
    }
  }
}

License

See the LICENSE file.

Documentation

Index

Constants

View Source
const (
	APIVersion = "v2"
	Charset    = "UTF-8"
)
View Source
const Version string = "2.1.9"

Variables

View Source
var (
	DefaultHTTPTimeout    = 80 * time.Second
	ExportWaitInSecs      = 3 * time.Second
	TimeMachineWaitInSecs = 3 * time.Second
	DefaultEnv            Environment
)

Functions

func Bool

func Bool(val bool) *bool

Bool returns a pointer to the bool value passed.

func BoolValue

func BoolValue(val *bool) bool

BoolValue returns the value of the bool pointer passed or false if the pointer is nil.

func Configure

func Configure(key string, siteName string)

func Do

func Do(req *http.Request, env Environment) (string, error)

Do is used to execute an API Request.

func ErrorHandling

func ErrorHandling(resBody []byte) error

func Float64

func Float64(val float64) *float64

Float64 returns a pointer to the float64 value passed.

func Float64Value

func Float64Value(val *float64) float64

Float64Value returns the value of the float64 pointer passed or 0 if the pointer is nil.

func GetMap

func GetMap(rawMessage json.RawMessage) map[string]interface{}

GetMap is used to unmarshal the json.RawMessage to map[string]interface{}.

func Int32

func Int32(val int32) *int32

Int32 returns a pointer to the int32 value passed.

func Int32Value

func Int32Value(val *int32) int32

Int32Value returns the value of the int32 pointer passed or 0 if the pointer is nil.

func Int64

func Int64(val int64) *int64

Int64 returns a pointer to the int64 value passed.

func Int64Value

func Int64Value(val *int64) int64

Int64Value returns the value of the int64 pointer passed or 0 if the pointer is nil.

func SerializeListParams

func SerializeListParams(params interface{}) *url.Values

SerializeListParams is to used to serialize the inputParams of list request.

func SerializeParams

func SerializeParams(params interface{}) *url.Values

SerializeParams is to used to serialize the inputParams request . Eg : Customer : { FirstName : "John" } is serialized as "customer[first_name]" : "John".

func UnmarshalJSON

func UnmarshalJSON(response []byte, result interface{}) error

UnmarshalJSON is used to unmarshal the response to Result / ResultList struct.

Types

type Environment

type Environment struct {
	Key             string
	SiteName        string
	ChargebeeDomain string
	Protocol        string
	HTTPClient      *http.Client
	BackoffConfig   backoff.BackOff
}

func DefaultConfig

func DefaultConfig() Environment

type Error

type Error struct {
	HTTPStatusCode int       `json:"http_status_code"`
	Msg            string    `json:"message"`
	Param          string    `json:"param"`
	APIErrorCode   string    `json:"api_error_code"`
	Type           ErrorType `json:"type"`
	ErrorCode      string    `json:"error_code"`
	Err            error     `json:"_"`
}

Error is the Response returned when a call is unsuccessful

func (*Error) Error

func (e *Error) Error() string

Error Serializes the error object to JSON and return it as a string.

type ErrorType

type ErrorType string

ErrorType is the list of allowed values for error type.

const (
	PaymentError         ErrorType = "payment"
	InvalidRequestError  ErrorType = "invalid_request"
	OperationFailedError ErrorType = "operation_failed"
)

type RequestObj

type RequestObj struct {
	Params *url.Values
	Method string
	Path   string
	Header map[string]string
}

RequestObj is the structure that contains the properties of any request data.

func Send

func Send(method string, path string, params interface{}) RequestObj

Send prepares a RequestObj for Request operation.

func SendList

func SendList(method string, path string, params interface{}) RequestObj

SendList prepares a RequestObj for ListRequest operation.

func (RequestObj) AddParams

func (request RequestObj) AddParams(key string, value interface{}) RequestObj

AddParams add a new key-value pair to the RequestObj.Params. This is used to add extra/custom_field params in the request data.

func (RequestObj) Headers

func (request RequestObj) Headers(key string, value string) RequestObj

Headers add a new key-value pair to the RequestObj.Header . This is used to add custom headers .

func (RequestObj) ListRequest

func (request RequestObj) ListRequest() (*ResultList, error)

func (RequestObj) ListRequestWithEnv

func (request RequestObj) ListRequestWithEnv(env Environment) (*ResultList, error)

func (RequestObj) Request

func (request RequestObj) Request() (*Result, error)

func (RequestObj) RequestWithEnv

func (request RequestObj) RequestWithEnv(env Environment) (*Result, error)

type Result

type Result struct {
	Subscription            *subscription.Subscription                       `json:"subscription,omitempty"`
	ContractTerm            *contractterm.ContractTerm                       `json:"contract_term,omitempty"`
	AdvanceInvoiceSchedule  *advanceinvoiceschedule.AdvanceInvoiceSchedule   `json:"advance_invoice_schedule,omitempty"`
	Customer                *customer.Customer                               `json:"customer,omitempty"`
	Hierarchy               *hierarchy.Hierarchy                             `json:"hierarchy,omitempty"`
	Contact                 *contact.Contact                                 `json:"contact,omitempty"`
	Token                   *token.Token                                     `json:"token,omitempty"`
	PaymentSource           *paymentsource.PaymentSource                     `json:"payment_source,omitempty"`
	ThirdPartyPaymentMethod *thirdpartypaymentmethod.ThirdPartyPaymentMethod `json:"third_party_payment_method,omitempty"`
	VirtualBankAccount      *virtualbankaccount.VirtualBankAccount           `json:"virtual_bank_account,omitempty"`
	Card                    *card.Card                                       `json:"card,omitempty"`
	PromotionalCredit       *promotionalcredit.PromotionalCredit             `json:"promotional_credit,omitempty"`
	Invoice                 *invoice.Invoice                                 `json:"invoice,omitempty"`
	CreditNote              *creditnote.CreditNote                           `json:"credit_note,omitempty"`
	UnbilledCharge          *unbilledcharge.UnbilledCharge                   `json:"unbilled_charge,omitempty"`
	Order                   *order.Order                                     `json:"order,omitempty"`
	Gift                    *gift.Gift                                       `json:"gift,omitempty"`
	Transaction             *transaction.Transaction                         `json:"transaction,omitempty"`
	HostedPage              *hostedpage.HostedPage                           `json:"hosted_page,omitempty"`
	Estimate                *estimate.Estimate                               `json:"estimate,omitempty"`
	Quote                   *quote.Quote                                     `json:"quote,omitempty"`
	QuotedSubscription      *quotedsubscription.QuotedSubscription           `json:"quoted_subscription,omitempty"`
	QuoteLineGroup          *quotelinegroup.QuoteLineGroup                   `json:"quote_line_group,omitempty"`
	Plan                    *plan.Plan                                       `json:"plan,omitempty"`
	Addon                   *addon.Addon                                     `json:"addon,omitempty"`
	Coupon                  *coupon.Coupon                                   `json:"coupon,omitempty"`
	CouponSet               *couponset.CouponSet                             `json:"coupon_set,omitempty"`
	CouponCode              *couponcode.CouponCode                           `json:"coupon_code,omitempty"`
	Address                 *address.Address                                 `json:"address,omitempty"`
	Usage                   *usage.Usage                                     `json:"usage,omitempty"`
	Event                   *event.Event                                     `json:"event,omitempty"`
	Comment                 *comment.Comment                                 `json:"comment,omitempty"`
	Download                *download.Download                               `json:"download,omitempty"`
	PortalSession           *portalsession.PortalSession                     `json:"portal_session,omitempty"`
	SiteMigrationDetail     *sitemigrationdetail.SiteMigrationDetail         `json:"site_migration_detail,omitempty"`
	ResourceMigration       *resourcemigration.ResourceMigration             `json:"resource_migration,omitempty"`
	TimeMachine             *timemachine.TimeMachine                         `json:"time_machine,omitempty"`
	Export                  *export.Export                                   `json:"export,omitempty"`
	PaymentIntent           *paymentintent.PaymentIntent                     `json:"payment_intent,omitempty"`
	ItemFamily              *itemfamily.ItemFamily                           `json:"item_family,omitempty"`
	Item                    *item.Item                                       `json:"item,omitempty"`
	ItemPrice               *itemprice.ItemPrice                             `json:"item_price,omitempty"`
	AttachedItem            *attacheditem.AttachedItem                       `json:"attached_item,omitempty"`
	DifferentialPrice       *differentialprice.DifferentialPrice             `json:"differential_price,omitempty"`
	UnbilledCharges         []*unbilledcharge.UnbilledCharge                 `json:"unbilled_charges,omitempty"`
	CreditNotes             []*creditnote.CreditNote                         `json:"credit_notes,omitempty"`
	AdvanceInvoiceSchedules []*advanceinvoiceschedule.AdvanceInvoiceSchedule `json:"advance_invoice_schedules,omitempty"`
	Hierarchies             []*hierarchy.Hierarchy                           `json:"hierarchies,omitempty"`
	Invoices                []*invoice.Invoice                               `json:"invoices,omitempty"`
	DifferentialPrices      []*differentialprice.DifferentialPrice           `json:"differential_prices,omitempty"`
}

type ResultList

type ResultList struct {
	List       []*Result `json:"list"`
	NextOffset string    `json:"next_offset"`
}

Directories

Path Synopsis
actions
models

Jump to

Keyboard shortcuts

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