chargebee

package module
v2.27.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2023 License: MIT Imports: 72 Imported by: 290

README

Go Client Library for Chargebee API


This is the source code for the Go client library for Chargebee APIs.

Go version: v3 and v2 of the library require Go v1.3 or higher.

Library versions


The versioning scheme of this library is inspired by SemVer and the format is v{MAJOR}.{MINOR}.{PATCH}. For example, v3.0.0 and v2.5.1 are valid library versions.

The following table provides some details for each major version:

Library major version Status Compatible API versions Branch
v3 Active v2 and v1 master
v2 Active v2 and v1 chargebee-v2

A couple of terms used in the above table are explained below:

  • Status: The current development status for the library version. An Active major version is currently being maintained and continues to get backward-compatible changes.
  • Branch: The branch in this repository containing the source code for the latest release of the library version. Every version of the library has been tagged. You can check out the source code for any version using its tag.

🔴 Attention: The support for v2 will eventually be discontinued on December 31st 2023 and will no longer receive any further updates. We strongly recommend upgrading to v3 as soon as possible.

Note: See the changelog for a history of changes.

Install the library


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

Install v3
go get github.com/chargebee/chargebee-go/v3
Install v2
go get github.com/chargebee/chargebee-go

Use the library


Some examples for using the library are listed below.

Create a customer and subscription
import (
  "fmt"
  "github.com/chargebee/chargebee-go/v3"
  subscriptionAction "github.com/chargebee/chargebee-go/v3/actions/subscription"
  "github.com/chargebee/chargebee-go/v3/models/subscription"
)

func main() {
  chargebee.Configure("{site_api_key}", "{site}")
  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
  }
}
Create a subscription with addons, metadata, and coupons
import (
  "fmt"
  "github.com/chargebee/chargebee-go/v3"
  subscriptionAction "github.com/chargebee/chargebee-go/v3/actions/subscription"
  "github.com/chargebee/chargebee-go/v3/models/subscription"
)

func main() {
  chargebee.Configure("{site_api_key}", "{site}")
  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
  }
}
Create a subscription with custom headers and custom fields and custom context
import (
  "fmt"
  "github.com/chargebee/chargebee-go/v3"
  subscriptionAction "github.com/chargebee/chargebee-go/v3/actions/subscription"
  "github.com/chargebee/chargebee-go/v3/models/subscription"
)

func main() {
  chargebee.Configure("{site_api_key}", "{site}")
  res, err := subscriptionAction.Create(&subscription.CreateRequestParams{
    PlanId: "cbdemo_grow",
  }).Headers("chargebee-request-origin-ip", "192.168.1.2").Contexts(ctx).AddParams("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
  }
}
Retrieve a filtered list of subscriptions
import (
  "fmt"
  "github.com/chargebee/chargebee-go/v3"
  subscriptionAction "github.com/chargebee/chargebee-go/v3/actions/subscription"
  "github.com/chargebee/chargebee-go/v3/filter"
  "github.com/chargebee/chargebee-go/v3/models/subscription"
)

func main() {
  chargebee.Configure("{site_api_key}", "{site}")
  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
  }
  }
}
Create an idempotent request

Idempotency keys are passed along with request headers to allow a safe retry of POST requests.

import (
	"fmt"
	"github.com/chargebee/chargebee-go/v3"
	customerAction "github.com/chargebee/chargebee-go/v3/actions/customer"
	"github.com/chargebee/chargebee-go/v3/models/customer"
)

func main() {
    chargebee.Configure("{site_api_key}", "{site}")
	res, err := customerAction.Create(&customer.CreateRequestParams{
		FirstName: "John",
		LastName:  "Doe",
		Email:     "john@test.com",
	})
	.SetIdempotencyKey("ghggh") // Replace <<UUID>> with a unique string
	.Request()
	if err != nil {
		fmt.Println(err)
	} else {
		Customer := res.Customer
		fmt.Println(Customer)
	}
  headerValue := res.GetResponseHeaders() // Retrieves response headers
	fmt.Println(headerValue)
  idempotencyReplayedValue := res.IsIdempotencyReplayed()// Retrieves idempotency replayed header value 
  fmt.Println(idempotencyReplayedValue)
}

IsIdempotencyReplayed() method can be accessed to differentiate between original and replayed requests.

Use the test suite


Use Testify's require package to run the test suite

go get github.com/stretchr/testify/require

Handle errors


_,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 == &lt;other card params&gt;){ 
            //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.     
    }
  }
}

Contribution


You may contribute patches to any of the Active versions of this library. To do so, raise a PR against the respective branch.

If you find something amiss, you are welcome to create an issue.

API documentation


The API documentation for the Go library can be found in our API reference.

License


See the LICENSE.


Documentation

Index

Constants

View Source
const (
	APIVersion = "v2"
	Charset    = "UTF-8"
)
View Source
const (
	IdempotencyHeader       = "chargebee-idempotency-key"
	IdempotencyReplayHeader = "Chargebee-Idempotency-Replayed"
)
View Source
const Version string = "2.27.0"

Variables

View Source
var (
	TotalHTTPTimeout      = 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 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 NewDefaultHTTPClient

func NewDefaultHTTPClient() *http.Client

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.

func UpdateTotalHTTPTimeout

func UpdateTotalHTTPTimeout(timeout time.Duration)

func WithHTTPClient

func WithHTTPClient(c *http.Client)

Types

type CBResponse

type CBResponse struct {
	Body []byte
	ResponseMeta
}

func Do

func Do(req *http.Request) (*CBResponse, error)

Do is used to execute an API Request.

type Environment

type Environment struct {
	Key             string
	SiteName        string
	ChargebeeDomain string
	Protocol        string
}

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
	Context context.Context `form:"-"`
}

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) Contexts

func (request RequestObj) Contexts(ctx context.Context) RequestObj

Context used for request. It may carry deadlines, cancelation signals, and other request-scoped values across API boundaries and between processes.

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)

func (RequestObj) SetIdempotencyKey

func (request RequestObj) SetIdempotencyKey(idempotencyKey string) RequestObj

This is used to add idempotency key .

type ResponseMeta

type ResponseMeta struct {
	Headers    http.Header
	Status     string
	StatusCode int
}

type Result

type Result struct {
	Subscription            *subscription.Subscription                       `json:"subscription,omitempty"`
	ContractTerm            *contractterm.ContractTerm                       `json:"contract_term,omitempty"`
	Discount                *discount.Discount                               `json:"discount,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"`
	PaymentReferenceNumber  *paymentreferencenumber.PaymentReferenceNumber   `json:"payment_reference_number,omitempty"`
	TaxWithheld             *taxwithheld.TaxWithheld                         `json:"tax_withheld,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"`
	QuotedCharge            *quotedcharge.QuotedCharge                       `json:"quoted_charge,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"`
	Feature                 *feature.Feature                                 `json:"feature,omitempty"`
	ImpactedSubscription    *impactedsubscription.ImpactedSubscription       `json:"impacted_subscription,omitempty"`
	ImpactedItem            *impacteditem.ImpactedItem                       `json:"impacted_item,omitempty"`
	SubscriptionEntitlement *subscriptionentitlement.SubscriptionEntitlement `json:"subscription_entitlement,omitempty"`
	ItemEntitlement         *itementitlement.ItemEntitlement                 `json:"item_entitlement,omitempty"`
	InAppSubscription       *inappsubscription.InAppSubscription             `json:"in_app_subscription,omitempty"`
	EntitlementOverride     *entitlementoverride.EntitlementOverride         `json:"entitlement_override,omitempty"`
	Purchase                *purchase.Purchase                               `json:"purchase,omitempty"`
	PaymentVoucher          *paymentvoucher.PaymentVoucher                   `json:"payment_voucher,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"`
	Downloads               []*download.Download                             `json:"downloads,omitempty"`
	Invoices                []*invoice.Invoice                               `json:"invoices,omitempty"`
	DifferentialPrices      []*differentialprice.DifferentialPrice           `json:"differential_prices,omitempty"`
	InAppSubscriptions      []*inappsubscription.InAppSubscription           `json:"in_app_subscriptions,omitempty"`
	// contains filtered or unexported fields
}

func (*Result) GetResponseHeaders

func (r *Result) GetResponseHeaders() http.Header

func (*Result) IsIdempotencyReplayed

func (r *Result) IsIdempotencyReplayed() bool

type ResultList

type ResultList struct {
	List       []*Result `json:"list"`
	NextOffset string    `json:"next_offset"`
	// contains filtered or unexported fields
}

func (*ResultList) GetResponseHeaders

func (rl *ResultList) GetResponseHeaders() http.Header

Directories

Path Synopsis
actions
models

Jump to

Keyboard shortcuts

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