hubspot

package module
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: May 26, 2026 License: Apache-2.0 Imports: 16 Imported by: 2

README

go-hubspot

godoc License

HubSpot Go Library that works with HubSpot API v3.
HubSpot officially supports client library of Node.js, PHP, Ruby, and Python but not Go.

Note: go-hubspot currently doesn't cover all the APIs but mainly implemented CRM APIs. Implemented APIs are used in production.

Install

$ go get github.com/belong-inc/go-hubspot

Usage

Authentication

API key

Deprecated

You should take api key in advance. Follow steps in here.

// Initialize hubspot client with apikey.
client, _ := hubspot.NewClient(hubspot.SetAPIKey("YOUR_API_KEY"))
OAuth

You should take refresh token in advance. Follow steps in here.

// Initialize hubspot client with OAuth refresh token.
client, _ := hubspot.NewClient(hubspot.SetOAuth(&hubspot.OAuthConfig{
    GrantType:    hubspot.GrantTypeRefreshToken,
    ClientID:     "YOUR_CLIENT_ID",
    ClientSecret: "YOUR_CLIENT_SECRET",
    RefreshToken: "YOUR_REFRESH_TOKEN",
}))
Private app

You should take access token in advance. Follow steps in here.

// Initialize hubspot client with private app access token.
client, _ := hubspot.NewClient(hubspot.SetPrivateAppToken("YOUR_ACCESS_TOKEN"))

API call

Get contact
// Initialize hubspot client with auth method.
client, _ := hubspot.NewClient(hubspot.SetPrivateAppToken("YOUR_ACCESS_TOKEN"))

// Get a Contact object whose id is `yourContactID`.
// Contact instance needs to be provided to bind response value.
res, _ := client.CRM.Contact.Get("yourContactID", &hubspot.Contact{}, nil)

// Type assertion to convert `interface` to `hubspot.Contact`.
contact, ok := res.Properties.(*hubspot.Contact)
if !ok {
    return errors.New("unable to assert type")
}

// Use contact fields.
fmt.Println(contact.FirstName, contact.LastName)

Create contact
// Initialize hubspot client with auth method.
client, _ := hubspot.NewClient(hubspot.SetPrivateAppToken("YOUR_ACCESS_TOKEN"))

// Create request payload.
req := &hubspot.Contact{
    Email:       hubspot.NewString("yourEmail"),
    FirstName:   hubspot.NewString("yourFirstName"),
    LastName:    hubspot.NewString("yourLastName"),
    MobilePhone: hubspot.NewString("yourMobilePhone"),
    Website:     hubspot.NewString("yourWebsite"),
    Zip:         nil,
}

// Call create contact api.
res, _ := client.CRM.Contact.Create(req)

// Type assertion to convert `interface` to `hubspot.Contact`.
contact, ok := res.Properties.(*hubspot.Contact)
if !ok {
    return errors.New("unable to assert type")
}

// Use contact fields.
fmt.Println(contact.FirstName, contact.LastName)

Associate objects
// Initialize hubspot client with auth method.
client, _ := hubspot.NewClient(hubspot.SetPrivateAppToken("YOUR_ACCESS_TOKEN"))

// Call associate api.
client.CRM.Contact.AssociateAnotherObj("yourContactID", &hubspot.AssociationConfig{
    ToObject:   hubspot.ObjectTypeDeal,
    ToObjectID: "yourDealID",
    Type:       hubspot.AssociationTypeContactToDeal,
})

API call using custom fields

Custom fields are added out of existing object such as Deal or Contact.
Therefore a new struct needs to be created which contain default fields and additional custom field, and set to Properties field of a request. Before using custom field through API, the field needs to be set up in HubSpot web site.

Get deal with custom fields.
type CustomDeal struct {
	hubspot.Deal // embed default fields.
	CustomA string `json:"custom_a,omitempty"`
	CustomB string `json:"custom_b,omitempty"`
}

// Initialize hubspot client with auth method.
client, _ := hubspot.NewClient(hubspot.SetPrivateAppToken("YOUR_ACCESS_TOKEN"))

// Get a Deal object whose id is `yourDealID`.
// CustomDeal instance needs to be provided as to bind response value contained custom fields.
res, _ := client.CRM.Deal.Get("yourDealID", &CustomDeal{}, &hubspot.RequestQueryOption{
    CustomProperties: []string{
        "custom_a",
        "custom_b",
    },
})

// Type assertion to convert `interface` to `CustomDeal`.
customDeal, ok := res.Properties.(*CustomDeal)
if !ok {
    return errors.New("unable to assert type")
}

// Use custom deal fields.
fmt.Println(customDeal.CustomA, customDeal.CustomB)

Create deal with custom properties.
type CustomDeal struct {
	hubspot.Deal // embed default fields.
	CustomA string `json:"custom_a,omitempty"`
	CustomB string `json:"custom_b,omitempty"`
}

// Initialize hubspot client with auth method.
client, _ := hubspot.NewClient(hubspot.SetPrivateAppToken("YOUR_ACCESS_TOKEN"))

req := &CustomDeal{
    Deal: hubspot.Deal{
        Amount:      hubspot.NewString("yourAmount"),
        DealName:    hubspot.NewString("yourDealName"),
        DealStage:   hubspot.NewString("yourDealStage"),
        DealOwnerID: hubspot.NewString("yourDealOwnerID"),
        PipeLine:    hubspot.NewString("yourPipeLine"),
    },
    CustomA: "yourCustomFieldA",
    CustomB: "yourCustomFieldB",
}

// Call create deal api with custom struct.
res, _ := client.CRM.Deal.Create(req)

// Type assertion to convert `interface` to `CustomDeal`.
customDeal, ok := res.Properties.(*CustomDeal)
if !ok {
    return errors.New("unable to type assertion")
}

// Use custom deal fields.
fmt.Println(customDeal.CustomA, customDeal.CustomB)

API availability

Category API Availability
CRM Deal Available
CRM Company Available
CRM Contact Available
CRM Imports Beta
CRM Schemas Beta
CRM Properties Beta
CRM Tickets Beta
CMS All Not Implemented
Conversations Visitor Identification Available
Events All Not Implemented
Marketing Marketing Email Available
Marketing Transactional Email Available
Files All Not Implemented
Settings All Not Implemented
Webhooks All Not Implemented

Authentication availability

Type Availability
API key Deprecated
OAuth Available
Private apps Available

Contributing

Contributions are generally welcome.
Please refer to CONTRIBUTING.md when making your contribution.

Documentation

Overview

Package hubspot is the root of packages used to access Hubspot APIs.

This library is targeting HubSpot API v3. Docs are available in https://developers.hubspot.com/docs/api/overview.

Index

Examples

Constants

View Source
const (
	// ValidationError is the APIError.Category.
	// This is returned by HubSpot when the HTTP Status is 400.
	// In this case, the verification details error will be included in Details
	ValidationError = "VALIDATION_ERROR"

	// InvalidEmailError is the value of ErrDetail.Error when an error occurs in the Email validation.
	InvalidEmailError = "INVALID_EMAIL"
	// UnknownDetailError is the value set by go-hubspot when extraction the error details failed.
	UnknownDetailError = "UNKNOWN_DETAIL"
)
View Source
const (
	// MIMETypeJSON is the mimetype for JSON.
	MIMETypeJSON = "application/json"
	// MIMETypeFormData is the mimetype for multipart form data.
	MIMETypeFormData = "multipart/form-data"
)
View Source
const (
	GrantTypeRefreshToken = "refresh_token"
)

Variables

View Source
var BlankStr = NewString("")

BlankStr should be used to include empty string in HubSpot fields. This is because fields set to `nil` will be ignored by omitempty.

Functions

func CheckResponseError

func CheckResponseError(r *http.Response) error

CheckResponseError checks the response, and in case of error, maps it to the error structure.

Types

type APIError

type APIError struct {
	HTTPStatusCode int         `json:"-"`
	Status         string      `json:"status,omitempty"`
	Message        string      `json:"message,omitempty"`
	CorrelationID  string      `json:"correlationId,omitempty"`
	Context        ErrContext  `json:"context,omitempty"`
	Category       string      `json:"category,omitempty"`
	SubCategory    string      `json:"subCategory,omitempty"`
	Links          ErrLinks    `json:"links,omitempty"`
	Details        []ErrDetail `json:"details,omitempty"`
}

func (APIError) Error

func (e APIError) Error() string

type APIKey

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

func (*APIKey) SetAuthentication

func (a *APIKey) SetAuthentication(r *http.Request) error

type AssociationConfig

type AssociationConfig struct {
	ToObject   ObjectType
	ToObjectID string
	Type       AssociationType
}

type AssociationResult

type AssociationResult struct {
	ID   string `json:"id"`
	Type string `json:"type"`
}

type AssociationType

type AssociationType string

AssociationType is the name of the key used to associate the objects together.

const (
	AssociationTypeContactToCompany    AssociationType = "contact_to_company"
	AssociationTypeContactToDeal       AssociationType = "contact_to_deal"
	AssociationTypeContactToEngagement AssociationType = "contact_to_engagement"
	AssociationTypeContactToTicket     AssociationType = "contact_to_ticket"

	AssociationTypeDealToContact    AssociationType = "deal_to_contact"
	AssociationTypeDealToCompany    AssociationType = "deal_to_company"
	AssociationTypeDealToEngagement AssociationType = "deal_to_engagement"
	AssociationTypeDealToLineItem   AssociationType = "deal_to_line_item"
	AssociationTypeDealToTicket     AssociationType = "deal_to_ticket"

	AssociationTypeCompanyToContact AssociationType = "company_to_contact"
	AssociationTypeCompanyToDeal    AssociationType = "company_to_deal"

	AssociationTypeNoteToDeal       AssociationType = "note_to_deal"
	AssociationTypeNoteToContact    AssociationType = "note_to_contact"
	AssociationTypeNoteToCompany    AssociationType = "note_to_company"
	AssociationTypeNoteToEngagement AssociationType = "note_to_engagement"
	AssociationTypeNoteToTicket     AssociationType = "note_to_ticket"
)

Default association types Reference: https://legacydocs.hubspot.com/docs/methods/crm-associations/crm-associations-overview

type Associations

type Associations struct {
	Contacts struct {
		Results []AssociationResult `json:"results"`
	} `json:"contacts"`
	Deals struct {
		Results []AssociationResult `json:"results"`
	} `json:"deals"`
	Companies struct {
		Results []AssociationResult `json:"results"`
	} `json:"companies"`
}

type AuthMethod

type AuthMethod func(c *Client)

func SetAPIKey deprecated

func SetAPIKey(key string) AuthMethod

Deprecated: Use hubspot.SetPrivateAppToken.

func SetOAuth

func SetOAuth(config *OAuthConfig) AuthMethod

func SetPrivateAppToken added in v0.3.0

func SetPrivateAppToken(token string) AuthMethod

type Authenticator

type Authenticator interface {
	SetAuthentication(r *http.Request) error
}

type BulkRequestQueryOption added in v0.2.0

type BulkRequestQueryOption struct {
	// Properties sets a comma separated list of the properties to be returned in the response.
	Properties []string `url:"properties,comma,omitempty"`
	// Limit is the maximum number of results to display per page.
	Limit int `url:"limit,comma,omitempty"`
	// After is the paging cursor token of the last successfully read resource will be returned as the paging.next.after.
	After string `url:"after,omitempty"`

	// Offset is used to get the next page of results.
	// Available only in API v1.
	Offset string `url:"offset,omitempty"`
	// orderBy is used to order by a particular field value.
	// Use a negative value to sort in descending order.
	// Available only in API v1.
	OrderBy string `url:"orderBy,omitempty"`
}

type BulkStatisticsResponse added in v0.2.0

type BulkStatisticsResponse = legacy.BulkResponseResource

BulkStatisticsResponse is response from marketing email statistics API v1 as of now. This contains list of Statistics.

type CRM

type CRM struct {
	Contact    ContactService
	Company    CompanyService
	Deal       DealService
	Imports    CrmImportsService
	Note       NoteService
	Schemas    CrmSchemasService
	Properties CrmPropertiesService
	Tickets    CrmTicketsService
}

type Client

type Client struct {
	HTTPClient *http.Client

	CRM          *CRM
	Marketing    *Marketing
	Conversation *Conversation
	// contains filtered or unexported fields
}

Client manages communication with the HubSpot API.

func NewClient

func NewClient(setAuthMethod AuthMethod, opts ...Option) (*Client, error)

NewClient returns a new HubSpot API client with APIKey or OAuthConfig. HubSpot officially recommends authentication with OAuth. e.g. hubspot.NewClient(hubspot.SetPrivateAppToken("key"))

func (*Client) CreateAndDo

func (c *Client) CreateAndDo(method, relPath, contentType string, data, option, resource interface{}) error

CreateAndDo performs a web request to HubSpot. The `data`, `options` and `resource` arguments are optional and only relevant in certain situations. If the data argument is non-nil, it will be used as the body of the request for POST and PUT requests. The options argument is used for specifying request options such as search parameters. The resource argument is marshalled data returned from HubSpot. If the resource contains a pointer to data, the data will be overwritten with the content of the response.

func (*Client) Delete

func (c *Client) Delete(path string, option interface{}) error

Delete performs a DELETE request for the given path.

func (*Client) Get

func (c *Client) Get(path string, resource interface{}, option interface{}) error

Get performs a GET request for the given path and saves the result in the given resource.

func (*Client) NewRequest

func (c *Client) NewRequest(method, path string, body, option interface{}, contentType string) (*http.Request, error)

NewRequest creates an API request. After creating a request, add the authentication information according to the method specified in NewClient().

func (*Client) Patch

func (c *Client) Patch(path string, data, resource interface{}) error

Patch performs a PATCH request for the given path and saves the result in the given resource.

func (*Client) Post

func (c *Client) Post(path string, data, resource interface{}) error

Post performs a POST request for the given path and saves the result in the given resource.

func (*Client) PostMultipart added in v0.5.0

func (c *Client) PostMultipart(path, boundary string, data, resource interface{}) error

func (*Client) Put

func (c *Client) Put(path string, data, resource interface{}) error

Put performs a PUT request for the given path and saves the result in the given resource.

type Company added in v0.7.0

type Company struct {
	AboutUs                                 *HsStr  `json:"about_us,omitempty"`
	Address                                 *HsStr  `json:"address,omitempty"`
	Address2                                *HsStr  `json:"address2,omitempty"`
	Annualrevenue                           *HsInt  `json:"annualrevenue,omitempty"`
	City                                    *HsStr  `json:"city,omitempty"`
	Closedate                               *HsTime `json:"closedate,omitempty"`
	Country                                 *HsStr  `json:"country,omitempty"`
	Createdate                              *HsTime `json:"createdate,omitempty"`
	DaysToClose                             *HsInt  `json:"days_to_close,omitempty"`
	Description                             *HsStr  `json:"description,omitempty"`
	Domain                                  *HsStr  `json:"domain,omitempty"`
	EngagementsLastMeetingBooked            *HsTime `json:"engagements_last_meeting_booked,omitempty"`
	EngagementsLastMeetingBookedCampaign    *HsStr  `json:"engagements_last_meeting_booked_campaign,omitempty"`
	EngagementsLastMeetingBookedMedium      *HsStr  `json:"engagements_last_meeting_booked_medium,omitempty"`
	EngagementsLastMeetingBookedSource      *HsStr  `json:"engagements_last_meeting_booked_source,omitempty"`
	FacebookCompanyPage                     *HsStr  `json:"facebook_company_page,omitempty"`
	Facebookfans                            *HsInt  `json:"facebookfans,omitempty"`
	FirstContactCreatedate                  *HsTime `json:"first_contact_createdate,omitempty"`
	FirstConversionDate                     *HsTime `json:"first_conversion_date,omitempty"`
	FirstConversionEventName                *HsStr  `json:"first_conversion_event_name,omitempty"`
	FirstDealCreatedDate                    *HsTime `json:"first_deal_created_date,omitempty"`
	FoundedYear                             *HsStr  `json:"founded_year,omitempty"`
	GoogleplusPage                          *HsStr  `json:"googleplus_page,omitempty"`
	HsAnalyticsFirstTimestamp               *HsTime `json:"hs_analytics_first_timestamp,omitempty"`
	HsAnalyticsFirstTouchConvertingCampaign *HsStr  `json:"hs_analytics_first_touch_converting_campaign,omitempty"`
	HsAnalyticsFirstVisitTimestamp          *HsTime `json:"hs_analytics_first_visit_timestamp,omitempty"`
	HsAnalyticsLastTimestamp                *HsTime `json:"hs_analytics_last_timestamp,omitempty"`
	HsAnalyticsLastTouchConvertingCampaign  *HsStr  `json:"hs_analytics_last_touch_converting_campaign,omitempty"`
	HsAnalyticsLastVisitTimestamp           *HsTime `json:"hs_analytics_last_visit_timestamp,omitempty"`
	HsAnalyticsLatestSource                 *HsStr  `json:"hs_analytics_latest_source,omitempty"`
	HsAnalyticsLatestSourceData1            *HsStr  `json:"hs_analytics_latest_source_data_1,omitempty"`
	HsAnalyticsLatestSourceData2            *HsStr  `json:"hs_analytics_latest_source_data_2,omitempty"`
	HsAnalyticsLatestSourceTimestamp        *HsTime `json:"hs_analytics_latest_source_timestamp,omitempty"`
	HsAnalyticsNumPageViews                 *HsInt  `json:"hs_analytics_num_page_views,omitempty"`
	HsAnalyticsNumVisits                    *HsInt  `json:"hs_analytics_num_visits,omitempty"`
	HsAnalyticsSource                       *HsStr  `json:"hs_analytics_source,omitempty"`
	HsAnalyticsSourceData1                  *HsStr  `json:"hs_analytics_source_data_1,omitempty"`
	HsAnalyticsSourceData2                  *HsStr  `json:"hs_analytics_source_data_2,omitempty"`
	HsCreatedByUserId                       *HsInt  `json:"hs_created_by_user_id,omitempty"`
	HsCreatedate                            *HsTime `json:"hs_createdate,omitempty"`
	HsIdealCustomerProfile                  *HsStr  `json:"hs_ideal_customer_profile,omitempty"`
	HsIsTargetAccount                       *HsBool `json:"hs_is_target_account,omitempty"`
	HsLastBookedMeetingDate                 *HsTime `json:"hs_last_booked_meeting_date,omitempty"`
	HsLastLoggedCallDate                    *HsTime `json:"hs_last_logged_call_date,omitempty"`
	HsLastOpenTaskDate                      *HsTime `json:"hs_last_open_task_date,omitempty"`
	HsLastSalesActivityTimestamp            *HsTime `json:"hs_last_sales_activity_timestamp,omitempty"`
	HsLastmodifieddate                      *HsTime `json:"hs_lastmodifieddate,omitempty"`
	HsLeadStatus                            *HsStr  `json:"hs_lead_status,omitempty"`
	HsMergedObjectIds                       *HsStr  `json:"hs_merged_object_ids,omitempty"`
	HsNumBlockers                           *HsInt  `json:"hs_num_blockers,omitempty"`
	HsNumChildCompanies                     *HsInt  `json:"hs_num_child_companies,omitempty"`
	HsNumContactsWithBuyingRoles            *HsInt  `json:"hs_num_contacts_with_buying_roles,omitempty"`
	HsNumDecisionMakers                     *HsInt  `json:"hs_num_decision_makers,omitempty"`
	HsNumOpenDeals                          *HsInt  `json:"hs_num_open_deals,omitempty"`
	HsObjectId                              *HsInt  `json:"hs_object_id,omitempty"`
	HsParentCompanyId                       *HsInt  `json:"hs_parent_company_id,omitempty"`
	HsTotalDealValue                        *HsInt  `json:"hs_total_deal_value,omitempty"`
	HubspotOwnerAssigneddate                *HsTime `json:"hubspot_owner_assigneddate,omitempty"`
	HubspotOwnerId                          *HsStr  `json:"hubspot_owner_id,omitempty"`
	HubspotTeamId                           *HsStr  `json:"hubspot_team_id,omitempty"`
	Industry                                *HsStr  `json:"industry,omitempty"`
	IsPublic                                *HsBool `json:"is_public,omitempty"`
	Lifecyclestage                          *HsStr  `json:"lifecyclestage,omitempty"`
	LinkedinCompanyPage                     *HsStr  `json:"linkedin_company_page,omitempty"`
	Linkedinbio                             *HsStr  `json:"linkedinbio,omitempty"`
	Name                                    *HsStr  `json:"name,omitempty"`
	NotesLastContacted                      *HsTime `json:"notes_last_contacted,omitempty"`
	NotesLastUpdated                        *HsTime `json:"notes_last_updated,omitempty"`
	NotesNextActivityDate                   *HsTime `json:"notes_next_activity_date,omitempty"`
	NumAssociatedContacts                   *HsInt  `json:"num_associated_contacts,omitempty"`
	NumAssociatedDeals                      *HsInt  `json:"num_associated_deals,omitempty"`
	NumContactedNotes                       *HsInt  `json:"num_contacted_notes,omitempty"`
	NumConversionEvents                     *HsInt  `json:"num_conversion_events,omitempty"`
	Numberofemployees                       *HsInt  `json:"numberofemployees,omitempty"`
	Phone                                   *HsStr  `json:"phone,omitempty"`
	RecentConversionDate                    *HsTime `json:"recent_conversion_date,omitempty"`
	RecentConversionEventName               *HsStr  `json:"recent_conversion_event_name,omitempty"`
	RecentDealAmount                        *HsInt  `json:"recent_deal_amount,omitempty"`
	RecentDealCloseDate                     *HsTime `json:"recent_deal_close_date,omitempty"`
	State                                   *HsStr  `json:"state,omitempty"`
	Timezone                                *HsStr  `json:"timezone,omitempty"`
	TotalMoneyRaised                        *HsStr  `json:"total_money_raised,omitempty"`
	TotalRevenue                            *HsInt  `json:"total_revenue,omitempty"`
	Twitterbio                              *HsStr  `json:"twitterbio,omitempty"`
	Twitterfollowers                        *HsInt  `json:"twitterfollowers,omitempty"`
	Twitterhandle                           *HsStr  `json:"twitterhandle,omitempty"`
	Type                                    *HsStr  `json:"type,omitempty"`
	WebTechnologies                         *HsStr  `json:"web_technologies,omitempty"`
	Website                                 *HsStr  `json:"website,omitempty"`
	Zip                                     *HsStr  `json:"zip,omitempty"`
}

type CompanyResult added in v0.10.0

type CompanyResult struct {
	ID         string  `json:"id"`
	Properties Company `json:"properties"`
	CreatedAt  string  `json:"createdAt"`
	UpdatedAt  string  `json:"updatedAt"`
	Archived   bool    `json:"archived"`
}

type CompanySearchRequest added in v0.10.0

type CompanySearchRequest struct {
	SearchOptions
}

type CompanySearchResponse added in v0.10.0

type CompanySearchResponse struct {
	Total   int64           `json:"total"`
	Results []CompanyResult `json:"results"`
}

CompanySearchResponse represents the response from searching companies.

type CompanyService added in v0.7.0

type CompanyService interface {
	Get(companyID string, company interface{}, option *RequestQueryOption) (*ResponseResource, error)
	Create(company interface{}) (*ResponseResource, error)
	Update(companyID string, company interface{}) (*ResponseResource, error)
	Delete(companyID string) error
	AssociateAnotherObj(companyID string, conf *AssociationConfig) (*ResponseResource, error)
	DeleteAssociation(companyID string, conf *AssociationConfig) error
	SearchByDomain(domain string) (*CompanySearchResponse, error)
	SearchByName(name string) (*CompanySearchResponse, error)
	Search(req *CompanySearchRequest) (*CompanySearchResponse, error)
}

CompanyService is an interface of company endpoints of the HubSpot API. HubSpot companies store information about organizations. It can also be associated with other CRM objects such as deal and contact. Reference: https://developers.hubspot.com/docs/api/crm/companies

type CompanyServiceOp added in v0.7.0

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

CompanyServiceOp handles communication with the product related methods of the HubSpot API.

func (*CompanyServiceOp) AssociateAnotherObj added in v0.7.0

func (s *CompanyServiceOp) AssociateAnotherObj(companyID string, conf *AssociationConfig) (*ResponseResource, error)

AssociateAnotherObj associates Company with another HubSpot objects. If you want to associate a custom object, please use a defined value in HubSpot.

func (*CompanyServiceOp) Create added in v0.7.0

func (s *CompanyServiceOp) Create(company interface{}) (*ResponseResource, error)

Create creates a new company. In order to bind the created content, a structure must be specified as an argument. When using custom fields, please embed hubspot.Company in your own structure.

func (*CompanyServiceOp) Delete added in v0.7.0

func (s *CompanyServiceOp) Delete(companyID string) error

Delete deletes a company.

func (*CompanyServiceOp) DeleteAssociation added in v0.11.0

func (s *CompanyServiceOp) DeleteAssociation(companyID string, conf *AssociationConfig) error

DeleteAssociation removes an association between Company and another HubSpot object. It is the inverse of AssociateAnotherObj.

func (*CompanyServiceOp) Get added in v0.7.0

func (s *CompanyServiceOp) Get(companyID string, company interface{}, option *RequestQueryOption) (*ResponseResource, error)

Get gets a Company. In order to bind the get content, a structure must be specified as an argument. Also, if you want to get a custom field, you need to specify the field name. If you specify a non-existent field, it will be ignored. e.g. &hubspot.RequestQueryOption{ Properties: []string{"custom_a", "custom_b"}}

func (*CompanyServiceOp) Search added in v0.10.0

Search searches for a company by any given property filters, including custom properties. EXPERIMENTAL: This method is experimental and the interface may change in the future to support custom properties.

func (*CompanyServiceOp) SearchByDomain added in v0.10.0

func (s *CompanyServiceOp) SearchByDomain(domain string) (*CompanySearchResponse, error)

SearchByDomain searches for a company by domain. EXPERIMENTAL: This method is experimental and the interface may change in the future to support custom properties.

func (*CompanyServiceOp) SearchByName added in v0.10.0

func (s *CompanyServiceOp) SearchByName(name string) (*CompanySearchResponse, error)

SearchByName searches for a company by name. EXPERIMENTAL: This method is experimental and the interface may change in the future to support custom properties.

func (*CompanyServiceOp) Update added in v0.7.0

func (s *CompanyServiceOp) Update(companyID string, company interface{}) (*ResponseResource, error)

Update updates a company. In order to bind the updated content, a structure must be specified as an argument. When using custom fields, please embed hubspot.Company in your own structure.

type Contact

type Contact struct {
	Address                                     *HsStr  `json:"address,omitempty"`
	AnnualRevenue                               *HsStr  `json:"annualrevenue,omitempty"`
	City                                        *HsStr  `json:"city,omitempty"`
	CloseDate                                   *HsTime `json:"closedate,omitempty"`
	Company                                     *HsStr  `json:"company,omitempty"`
	CompanySize                                 *HsStr  `json:"company_size,omitempty"`
	Country                                     *HsStr  `json:"country,omitempty"`
	CreateDate                                  *HsTime `json:"createdate,omitempty"`
	CurrentlyInWorkflow                         *HsStr  `json:"currentlyinworkflow,omitempty"`
	DateOfBirth                                 *HsStr  `json:"date_of_birth,omitempty"`
	DaysToClose                                 *HsStr  `json:"days_to_close,omitempty"`
	Degree                                      *HsStr  `json:"degree,omitempty"`
	Email                                       *HsStr  `json:"email,omitempty"`
	EngagementsLastMeetingBooked                *HsTime `json:"engagements_last_meeting_booked,omitempty"`
	EngagementsLastMeetingBookedCampaign        *HsStr  `json:"engagements_last_meeting_booked_campaign,omitempty"`
	EngagementsLastMeetingBookedMedium          *HsStr  `json:"engagements_last_meeting_booked_medium,omitempty"`
	EngagementsLastMeetingBookedSource          *HsStr  `json:"engagements_last_meeting_booked_source,omitempty"`
	Fax                                         *HsStr  `json:"fax,omitempty"`
	FieldOfStudy                                *HsStr  `json:"field_of_study,omitempty"`
	FirstConversionDate                         *HsTime `json:"first_conversion_date,omitempty"`
	FirstConversionEventName                    *HsStr  `json:"first_conversion_event_name,omitempty"`
	FirstDealCreatedDate                        *HsTime `json:"first_deal_created_date,omitempty"`
	FirstName                                   *HsStr  `json:"firstname,omitempty"`
	Gender                                      *HsStr  `json:"gender,omitempty"`
	GraduationDate                              *HsStr  `json:"graduation_date,omitempty"`
	HsAnalyticsAveragePageViews                 *HsStr  `json:"hs_analytics_average_page_views,omitempty"`
	HsAnalyticsFirstReferrer                    *HsStr  `json:"hs_analytics_first_referrer,omitempty"`
	HsAnalyticsFirstTimestamp                   *HsTime `json:"hs_analytics_first_timestamp,omitempty"`
	HsAnalyticsFirstTouchConvertingCampaign     *HsStr  `json:"hs_analytics_first_touch_converting_campaign,omitempty"`
	HsAnalyticsFirstURL                         *HsStr  `json:"hs_analytics_first_url,omitempty"`
	HsAnalyticsFirstVisitTimestamp              *HsTime `json:"hs_analytics_first_visit_timestamp,omitempty"`
	HsAnalyticsLastReferrer                     *HsStr  `json:"hs_analytics_last_referrer,omitempty"`
	HsAnalyticsLastTimestamp                    *HsTime `json:"hs_analytics_last_timestamp,omitempty"`
	HsAnalyticsLastTouchConvertingCampaign      *HsStr  `json:"hs_analytics_last_touch_converting_campaign,omitempty"`
	HsAnalyticsLastURL                          *HsStr  `json:"hs_analytics_last_url,omitempty"`
	HsAnalyticsLastVisitTimestamp               *HsTime `json:"hs_analytics_last_visit_timestamp,omitempty"`
	HsAnalyticsNumEventCompletions              *HsStr  `json:"hs_analytics_num_event_completions,omitempty"`
	HsAnalyticsNumPageViews                     *HsStr  `json:"hs_analytics_num_page_views,omitempty"`
	HsAnalyticsNumVisits                        *HsStr  `json:"hs_analytics_num_visits,omitempty"`
	HsAnalyticsRevenue                          *HsStr  `json:"hs_analytics_revenue,omitempty"`
	HsAnalyticsSource                           *HsStr  `json:"hs_analytics_source,omitempty"`
	HsAnalyticsSourceData1                      *HsStr  `json:"hs_analytics_source_data_1,omitempty"`
	HsAnalyticsSourceData2                      *HsStr  `json:"hs_analytics_source_data_2,omitempty"`
	HsBuyingRole                                *HsStr  `json:"hs_buying_role,omitempty"`
	HsContentMembershipEmailConfirmed           HsBool  `json:"hs_content_membership_email_confirmed,omitempty"`
	HsContentMembershipNotes                    *HsStr  `json:"hs_content_membership_notes,omitempty"`
	HsContentMembershipRegisteredAt             *HsTime `json:"hs_content_membership_registered_at,omitempty"`
	HsContentMembershipRegistrationDomainSentTo *HsStr  `json:"hs_content_membership_registration_domain_sent_to,omitempty"`
	HsContentMembershipRegistrationEmailSentAt  *HsTime `json:"hs_content_membership_registration_email_sent_at,omitempty"`
	HsContentMembershipStatus                   *HsStr  `json:"hs_content_membership_status,omitempty"`
	HsCreateDate                                *HsTime `json:"hs_createdate,omitempty"`
	HsEmailBadAddress                           HsBool  `json:"hs_email_bad_address,omitempty"`
	HsEmailBounce                               *HsStr  `json:"hs_email_bounce,omitempty"`
	HsEmailClick                                *HsStr  `json:"hs_email_click,omitempty"`
	HsEmailClickDate                            *HsTime `json:"hs_email_first_click_date,omitempty"`
	HsEmailDelivered                            *HsStr  `json:"hs_email_delivered,omitempty"`
	HsEmailDomain                               *HsStr  `json:"hs_email_domain,omitempty"`
	HsEmailFirstOpenDate                        *HsTime `json:"hs_email_first_open_date,omitempty"`
	HsEmailFirstSendDate                        *HsTime `json:"hs_email_first_send_date,omitempty"`
	HsEmailHardBounceReasonEnum                 *HsStr  `json:"hs_email_hard_bounce_reason_enum,omitempty"`
	HsEmailLastClickDate                        *HsTime `json:"hs_email_last_click_date,omitempty"`
	HsEmailLastEmailName                        *HsStr  `json:"hs_email_last_email_name,omitempty"`
	HsEmailLastOpenDate                         *HsTime `json:"hs_email_last_open_date,omitempty"`
	HsEmailLastSendDate                         *HsTime `json:"hs_email_last_send_date,omitempty"`
	HsEmailOpen                                 *HsStr  `json:"hs_email_open,omitempty"`
	HsEmailOpenDate                             *HsTime `json:"hs_email_open_date,omitempty"`
	HsEmailOptOut                               HsBool  `json:"hs_email_optout,omitempty"`
	HsEmailOptOut6766004                        *HsStr  `json:"hs_email_optout_6766004,omitempty"`
	HsEmailOptOut6766098                        *HsStr  `json:"hs_email_optout_6766098,omitempty"`
	HsEmailOptOut6766099                        *HsStr  `json:"hs_email_optout_6766099,omitempty"`
	HsEmailOptOut6766130                        *HsStr  `json:"hs_email_optout_6766130,omitempty"`
	HsEmailQuarantined                          HsBool  `json:"hs_email_quarantined,omitempty"`
	HsEmailSendsSinceLastEngagement             *HsStr  `json:"hs_email_sends_since_last_engagement,omitempty"`
	HsEmailConfirmationStatus                   *HsStr  `json:"hs_emailconfirmationstatus,omitempty"`
	HsFeedbackLastNpsFollowUp                   *HsStr  `json:"hs_feedback_last_nps_follow_up,omitempty"`
	HsFeedbackLastNpsRating                     *HsStr  `json:"hs_feedback_last_nps_rating,omitempty"`
	HsFeedbackLastSurveyDate                    *HsTime `json:"hs_feedback_last_survey_date,omitempty"`
	HsIPTimezone                                *HsStr  `json:"hs_ip_timezone,omitempty"`
	HsIsUnworked                                *HsStr  `json:"hs_is_unworked,omitempty"`
	HsLanguage                                  *HsStr  `json:"hs_language,omitempty"`
	HsLastSalesActivityTimestamp                *HsTime `json:"hs_last_sales_activity_timestamp,omitempty"`
	HsLeadStatus                                *HsStr  `json:"hs_lead_status,omitempty"`
	HsLifeCycleStageCustomerDate                *HsTime `json:"hs_lifecyclestage_customer_date,omitempty"`
	HsLifeCycleStageEvangelistDate              *HsTime `json:"hs_lifecyclestage_evangelist_date,omitempty"`
	HsLifeCycleStageLeadDate                    *HsTime `json:"hs_lifecyclestage_lead_date,omitempty"`
	HsLifeCycleStageMarketingQualifiedLeadDate  *HsTime `json:"hs_lifecyclestage_marketingqualifiedlead_date,omitempty"`
	HsLifeCycleStageOpportunityDate             *HsTime `json:"hs_lifecyclestage_opportunity_date,omitempty"`
	HsLifeCycleStageOtherDate                   *HsTime `json:"hs_lifecyclestage_other_date,omitempty"`
	HsLifeCycleStageSalesQualifiedLeadDate      *HsTime `json:"hs_lifecyclestage_salesqualifiedlead_date,omitempty"`
	HsLifeCycleStageSubscriberDate              *HsTime `json:"hs_lifecyclestage_subscriber_date,omitempty"`
	HsMarketableReasonID                        *HsStr  `json:"hs_marketable_reason_id,omitempty"`
	HsMarketableReasonType                      *HsStr  `json:"hs_marketable_reason_type,omitempty"`
	HsMarketableStatus                          *HsStr  `json:"hs_marketable_status,omitempty"`
	HsMarketableUntilRenewal                    *HsStr  `json:"hs_marketable_until_renewal,omitempty"`
	HsObjectID                                  *HsStr  `json:"hs_object_id,omitempty"`
	HsPersona                                   *HsStr  `json:"hs_persona,omitempty"`
	HsPredictiveContactScoreV2                  *HsStr  `json:"hs_predictivecontactscore_v2,omitempty"`
	HsPredictiveScoringTier                     *HsStr  `json:"hs_predictivescoringtier,omitempty"`
	HsSalesEmailLastClicked                     *HsTime `json:"hs_sales_email_last_clicked,omitempty"`
	HsSalesEmailLastOpened                      *HsTime `json:"hs_sales_email_last_opened,omitempty"`
	HsSalesEmailLastReplied                     *HsTime `json:"hs_sales_email_last_replied,omitempty"`
	HsSequencesIsEnrolled                       HsBool  `json:"hs_sequences_is_enrolled,omitempty"`
	HubspotOwnerAssignedDate                    *HsTime `json:"hubspot_owner_assigneddate,omitempty"`
	HubspotOwnerID                              *HsStr  `json:"hubspot_owner_id,omitempty"`
	HubspotTeamID                               *HsStr  `json:"hubspot_team_id,omitempty"`
	HubspotScore                                *HsStr  `json:"hubspotscore,omitempty"`
	Industry                                    *HsStr  `json:"industry,omitempty"`
	IPCity                                      *HsStr  `json:"ip_city,omitempty"`
	IPCountry                                   *HsStr  `json:"ip_country,omitempty"`
	IPCountryCode                               *HsStr  `json:"ip_country_code,omitempty"`
	IPState                                     *HsStr  `json:"ip_state,omitempty"`
	IPStateCode                                 *HsStr  `json:"ip_state_code,omitempty"`
	JobFunction                                 *HsStr  `json:"job_function,omitempty"`
	JobTitle                                    *HsStr  `json:"jobtitle,omitempty"`
	LastModifiedDate                            *HsTime `json:"lastmodifieddate,omitempty"`
	LastName                                    *HsStr  `json:"lastname,omitempty"`
	LifeCycleStage                              *HsStr  `json:"lifecyclestage,omitempty"`
	MaritalStatus                               *HsStr  `json:"marital_status,omitempty"`
	Message                                     *HsStr  `json:"message,omitempty"`
	MilitaryStatus                              *HsStr  `json:"military_status,omitempty"`
	MobilePhone                                 *HsStr  `json:"mobilephone,omitempty"`
	NotesLastContacted                          *HsTime `json:"notes_last_contacted,omitempty"`
	NotesLastUpdated                            *HsTime `json:"notes_last_updated,omitempty"`
	NotesNextActivityDate                       *HsTime `json:"notes_next_activity_date,omitempty"`
	NumAssociatedDeals                          *HsStr  `json:"num_associated_deals,omitempty"`
	NumContactedNotes                           *HsStr  `json:"num_contacted_notes,omitempty"`
	NumNotes                                    *HsStr  `json:"num_notes,omitempty"`
	NumUniqueConversionEvents                   *HsStr  `json:"num_unique_conversion_events,omitempty"`
	NumEmployees                                *HsStr  `json:"numemployees,omitempty"`
	RecentConversionDate                        *HsTime `json:"recent_conversion_date,omitempty"`
	RecentConversionEventName                   *HsStr  `json:"recent_conversion_event_name,omitempty"`
	RecentDealAmount                            *HsStr  `json:"recent_deal_amount,omitempty"`
	RecentDealCloseDate                         *HsTime `json:"recent_deal_close_date,omitempty"`
	RelationshipStatus                          *HsStr  `json:"relationship_status,omitempty"`
	Salutation                                  *HsStr  `json:"salutation,omitempty"`
	School                                      *HsStr  `json:"school,omitempty"`
	Seniority                                   *HsStr  `json:"seniority,omitempty"`
	StartDate                                   *HsStr  `json:"start_date,omitempty"`
	State                                       *HsStr  `json:"state,omitempty"`
	TotalRevenue                                *HsStr  `json:"total_revenue,omitempty"`
	Website                                     *HsStr  `json:"website,omitempty"`
	WorkEmail                                   *HsStr  `json:"work_email,omitempty"`
	Zip                                         *HsStr  `json:"zip,omitempty"`
}

type ContactResult added in v0.10.0

type ContactResult struct {
	ID         string  `json:"id"`
	Properties Contact `json:"properties"`
	CreatedAt  string  `json:"createdAt"`
	UpdatedAt  string  `json:"updatedAt"`
	Archived   bool    `json:"archived"`
}

type ContactSearchRequest added in v0.10.0

type ContactSearchRequest struct {
	SearchOptions
}

ContactSearchRequest represents the request body for searching contacts.

type ContactSearchResponse added in v0.10.0

type ContactSearchResponse struct {
	Total   int64           `json:"total"`
	Results []ContactResult `json:"results"`
}

ContactSearchResponse represents the response from searching contacts.

type ContactService

type ContactService interface {
	Get(contactID string, contact interface{}, option *RequestQueryOption) (*ResponseResource, error)
	Create(contact interface{}) (*ResponseResource, error)
	Update(contactID string, contact interface{}) (*ResponseResource, error)
	Delete(contactID string) error
	AssociateAnotherObj(contactID string, conf *AssociationConfig) (*ResponseResource, error)
	DeleteAssociation(contactID string, conf *AssociationConfig) error
	SearchByEmail(email string) (*ContactSearchResponse, error)
	Search(req *ContactSearchRequest) (*ContactSearchResponse, error)
}

ContactService is an interface of contact endpoints of the HubSpot API. HubSpot contacts store information about individuals. It can also be associated with other CRM objects such as deal and company. Reference: https://developers.hubspot.com/docs/api/crm/contacts

type ContactServiceOp

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

ContactServiceOp handles communication with the product related methods of the HubSpot API.

func (*ContactServiceOp) AssociateAnotherObj

func (s *ContactServiceOp) AssociateAnotherObj(contactID string, conf *AssociationConfig) (*ResponseResource, error)

AssociateAnotherObj associates Contact with another HubSpot objects. If you want to associate a custom object, please use a defined value in HubSpot.

Example
package main

import (
	"fmt"
	"log"
	"os"

	hubspot "github.com/belong-inc/go-hubspot"
)

func main() {
	cli, _ := hubspot.NewClient(hubspot.SetPrivateAppToken(os.Getenv("PRIVATE_APP_TOKEN")))

	res, err := cli.CRM.Contact.AssociateAnotherObj("contact001", &hubspot.AssociationConfig{
		ToObject:   hubspot.ObjectTypeDeal,
		ToObjectID: "deal001",
		Type:       hubspot.AssociationTypeContactToDeal,
	})
	if err != nil {
		log.Fatal(err)
	}

	r, ok := res.Properties.(*hubspot.Contact)
	if !ok {
		log.Fatal("unable to type assertion")
	}

	// use properties
	_ = r

	fmt.Println(res)

	// // Output:
}

func (*ContactServiceOp) Create

func (s *ContactServiceOp) Create(contact interface{}) (*ResponseResource, error)

Create creates a new contact. In order to bind the created content, a structure must be specified as an argument. When using custom fields, please embed hubspot.Contact in your own structure.

Example
package main

import (
	"fmt"
	"log"
	"os"

	hubspot "github.com/belong-inc/go-hubspot"
)

type ExampleContact struct {
	email     string
	firstName string
	lastName  string
	phone     string
	zip       string
}

func main() {
	cli, _ := hubspot.NewClient(hubspot.SetPrivateAppToken(os.Getenv("PRIVATE_APP_TOKEN")))

	example := &ExampleContact{
		email:     "hubspot@example.com",
		firstName: "Bryan",
		lastName:  "Cooper",
		phone:     "(877) 929-0687",
	}

	contact := &hubspot.Contact{
		Email:       hubspot.NewString(example.email),
		FirstName:   hubspot.NewString(example.firstName),
		LastName:    hubspot.NewString(example.lastName),
		MobilePhone: hubspot.NewString(example.phone),
		Website:     hubspot.NewString("example.com"),
		Zip:         nil,
	}

	res, err := cli.CRM.Contact.Create(contact)
	if err != nil {
		log.Fatal(err)
	}

	r, ok := res.Properties.(*hubspot.Contact)
	if !ok {
		log.Fatal("unable to type assertion")
	}

	// use properties
	_ = r

	fmt.Println(res)

	// // Output:
}

func (*ContactServiceOp) Delete added in v0.5.0

func (s *ContactServiceOp) Delete(contactID string) error

Delete deletes a contact.

func (*ContactServiceOp) DeleteAssociation added in v0.11.0

func (s *ContactServiceOp) DeleteAssociation(contactID string, conf *AssociationConfig) error

DeleteAssociation removes an association between Contact and another HubSpot object. It is the inverse of AssociateAnotherObj.

func (*ContactServiceOp) Get

func (s *ContactServiceOp) Get(contactID string, contact interface{}, option *RequestQueryOption) (*ResponseResource, error)

Get gets a contact. In order to bind the get content, a structure must be specified as an argument. Also, if you want to get a custom field, you need to specify the field name. If you specify a non-existent field, it will be ignored. e.g. &hubspot.RequestQueryOption{ Properties: []string{"custom_a", "custom_b"}}

Example
package main

import (
	"fmt"
	"log"
	"os"

	hubspot "github.com/belong-inc/go-hubspot"
)

func main() {
	cli, _ := hubspot.NewClient(hubspot.SetPrivateAppToken(os.Getenv("PRIVATE_APP_TOKEN")))

	res, err := cli.CRM.Contact.Get("contact001", &hubspot.Contact{}, nil)
	if err != nil {
		log.Fatal(err)
	}

	r, ok := res.Properties.(*hubspot.Contact)
	if !ok {
		log.Fatal("unable to type assertion")
	}

	// use properties
	_ = r

	fmt.Println(res)

	// // Output:
}

func (*ContactServiceOp) Search added in v0.10.0

Search searches for a contact by any given property filters, including custom properties. EXPERIMENTAL: This method is experimental and the interface may change in the future to support custom properties.

func (*ContactServiceOp) SearchByEmail added in v0.10.0

func (s *ContactServiceOp) SearchByEmail(email string) (*ContactSearchResponse, error)

SearchByEmail searches for a contact by email. EXPERIMENTAL: This method is experimental and the interface may change in the future to support custom properties.

func (*ContactServiceOp) Update

func (s *ContactServiceOp) Update(contactID string, contact interface{}) (*ResponseResource, error)

Update updates a contact. In order to bind the updated content, a structure must be specified as an argument. When using custom fields, please embed hubspot.Contact in your own structure.

Example
package main

import (
	"fmt"
	"log"
	"os"

	hubspot "github.com/belong-inc/go-hubspot"
)

type ExampleContact struct {
	email     string
	firstName string
	lastName  string
	phone     string
	zip       string
}

func main() {
	cli, _ := hubspot.NewClient(hubspot.SetPrivateAppToken(os.Getenv("PRIVATE_APP_TOKEN")))

	example := &ExampleContact{
		email:     "hubspot@example.com",
		firstName: "Bryan",
		lastName:  "Cooper",
		phone:     "(877) 929-0687",
		zip:       "1000001",
	}

	contact := &hubspot.Contact{
		Email:       hubspot.NewString(example.email),
		FirstName:   hubspot.NewString(example.firstName),
		LastName:    hubspot.NewString(example.lastName),
		MobilePhone: hubspot.NewString(example.phone),
		Website:     hubspot.NewString("example.com"),
		Zip:         hubspot.NewString(example.zip),
	}

	res, err := cli.CRM.Contact.Update("contact001", contact)
	if err != nil {
		log.Fatal(err)
	}

	r, ok := res.Properties.(*hubspot.Contact)
	if !ok {
		log.Fatal("unable to type assertion")
	}

	// use properties
	_ = r

	fmt.Println(res)

	// // Output:
}

type Conversation added in v0.8.0

type Conversation struct {
	VisitorIdentification VisitorIdentificationService
}

type CrmActiveImportOptions added in v0.5.0

type CrmActiveImportOptions struct {
	Before string `url:"before,omitempty"`
	After  string `url:"after,omitempty"`
	Offset int    `url:"offset,omitempty"`
}

type CrmImportColumnMapping added in v0.5.0

type CrmImportColumnMapping struct {
	ColumnObjectTypeId string `json:"columnObjectTypeId"`
	ColumnName         string `json:"columnName"`
	PropertyName       string `json:"propertyName"`
	IdColumnType       string `json:"idColumnType,omitempty"`
}

type CrmImportConfig added in v0.5.0

type CrmImportConfig struct {
	Name                    string                `json:"name"`
	MarketableContactImport bool                  `json:"marketableContactImport"`
	ImportOperations        map[string]string     `json:"importOperations"`
	Files                   []CrmImportFileConfig `json:"files"`
}

type CrmImportErrorsOptions added in v0.5.0

type CrmImportErrorsOptions struct {
	After string `url:"after,omitempty"`
	Limit int    `url:"limit,omitempty"`
}

type CrmImportFileConfig added in v0.5.0

type CrmImportFileConfig struct {
	FileName       string                  `json:"fileName"`
	FileFormat     string                  `json:"fileFormat"`
	DateFormat     string                  `json:"dateFormat"`
	FileImportPage CrmImportFilePageConfig `json:"fileImportPage"`
	// Data is the CSV or Spreadsheet data for this file.
	Data io.Reader `json:"-"`
}

type CrmImportFilePageConfig added in v0.5.0

type CrmImportFilePageConfig struct {
	HasHeader      bool                     `json:"hasHeader"`
	ColumnMappings []CrmImportColumnMapping `json:"columnMappings"`
}

type CrmImportsService added in v0.5.0

type CrmImportsService interface {
	Active(option *CrmActiveImportOptions) (interface{}, error)
	Get(int64) (interface{}, error)
	Cancel(int64) (interface{}, error)
	Errors(int64, *CrmImportErrorsOptions) (interface{}, error)
	Start(*CrmImportConfig) (interface{}, error)
}

CrmImportsService is an interface of CRM bulk import endpoints of the HubSpot API. Reference: https://developers.hubspot.com/docs/api/crm/imports

type CrmImportsServiceOp added in v0.5.0

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

CrmImportsServiceOp handles communication with the bulk CRM import endpoints of the HubSpot API.

func (*CrmImportsServiceOp) Active added in v0.5.0

func (s *CrmImportsServiceOp) Active(option *CrmActiveImportOptions) (interface{}, error)

func (*CrmImportsServiceOp) Cancel added in v0.5.0

func (s *CrmImportsServiceOp) Cancel(importId int64) (interface{}, error)

func (*CrmImportsServiceOp) Errors added in v0.5.0

func (s *CrmImportsServiceOp) Errors(importId int64, option *CrmImportErrorsOptions) (interface{}, error)

func (*CrmImportsServiceOp) Get added in v0.5.0

func (s *CrmImportsServiceOp) Get(importId int64) (interface{}, error)

func (*CrmImportsServiceOp) Start added in v0.5.0

func (s *CrmImportsServiceOp) Start(importRequest *CrmImportConfig) (interface{}, error)

type CrmPropertiesList added in v0.5.0

type CrmPropertiesList struct {
	Results []*CrmProperty `json:"results,omitempty"`
}

type CrmPropertiesService added in v0.5.0

type CrmPropertiesService interface {
	List(objectType string) (*CrmPropertiesList, error)
	Create(objectType string, reqData interface{}) (*CrmProperty, error)
	Get(objectType string, propertyName string) (*CrmProperty, error)
	Delete(objectType string, propertyName string) error
	Update(objectType string, propertyName string, reqData interface{}) (*CrmProperty, error)
}

CrmPropertiesService is an interface of CRM properties endpoints of the HubSpot API. Reference: https://developers.hubspot.com/docs/api/crm/properties

type CrmPropertiesServiceOp added in v0.5.0

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

CrmPropertiesServiceOp handles communication with the CRM properties endpoint.

func (*CrmPropertiesServiceOp) Create added in v0.5.0

func (s *CrmPropertiesServiceOp) Create(objectType string, reqData interface{}) (*CrmProperty, error)

func (*CrmPropertiesServiceOp) Delete added in v0.5.0

func (s *CrmPropertiesServiceOp) Delete(objectType string, propertyName string) error

func (*CrmPropertiesServiceOp) Get added in v0.5.0

func (s *CrmPropertiesServiceOp) Get(objectType, propertyName string) (*CrmProperty, error)

func (*CrmPropertiesServiceOp) List added in v0.5.0

func (s *CrmPropertiesServiceOp) List(objectType string) (*CrmPropertiesList, error)

func (*CrmPropertiesServiceOp) Update added in v0.5.0

func (s *CrmPropertiesServiceOp) Update(objectType string, propertyName string, reqData interface{}) (*CrmProperty, error)

type CrmProperty added in v0.5.0

type CrmProperty struct {
	UpdatedAt            *HsTime                      `json:"updatedAt,omitempty"`
	CreatedAt            *HsTime                      `json:"createdAt,omitempty"`
	ArchivedAt           *HsTime                      `json:"archivedAt,omitempty"`
	Name                 *HsStr                       `json:"name,omitempty"`
	Label                *HsStr                       `json:"label,omitempty"`
	Type                 *HsStr                       `json:"type,omitempty"`
	FieldType            *HsStr                       `json:"fieldType,omitempty"`
	Description          *HsStr                       `json:"description,omitempty"`
	GroupName            *HsStr                       `json:"groupName,omitempty"`
	Options              []*CrmPropertyOptions        `json:"options,omitempty"`
	CreatedUserId        *HsStr                       `json:"createdUserId,omitempty"`
	UpdatedUserId        *HsStr                       `json:"updatedUserId,omitempty"`
	ReferencedObjectType *HsStr                       `json:"referencedObjectType,omitempty"`
	DisplayOrder         *HsInt                       `json:"displayOrder,omitempty"`
	Calculated           *HsBool                      `json:"calculated,omitempty"`
	ExternalOptions      *HsBool                      `json:"externalOptions,omitempty"`
	Archived             *HsBool                      `json:"archived,omitempty"`
	HasUniqueValue       *HsBool                      `json:"hasUniqueValue,omitempty"`
	Hidden               *HsBool                      `json:"hidden,omitempty"`
	HubspotDefined       *HsBool                      `json:"hubspotDefined,omitempty"`
	ShowCurrencySymbol   *HsBool                      `json:"showCurrencySymbol,omitempty"`
	ModificationMetaData *CrmPropertyModificationMeta `json:"modificationMetadata,omitempty"`
	FormField            *HsBool                      `json:"formField,omitempty"`
	CalculationFormula   *HsStr                       `json:"calculationFormula,omitempty"`
}

type CrmPropertyModificationMeta added in v0.5.0

type CrmPropertyModificationMeta struct {
	Archivable       *HsBool `json:"archivable,omitempty"`
	ReadOnlyDefition *HsBool `json:"readOnlyDefinition,omitempty"`
	ReadOnlyValue    *HsBool `json:"readOnlyValue,omitempty"`
	ReadOnlyOptions  *HsBool `json:"readOnlyOptions,omitempty"`
}

type CrmPropertyOptions added in v0.5.0

type CrmPropertyOptions struct {
	Label        *HsStr  `json:"label,omitempty"`
	Value        *HsStr  `json:"value,omitempty"`
	Description  *HsStr  `json:"description,omitempty"`
	DisplayOrder *HsInt  `json:"displayOrder,omitempty"`
	Hidden       *HsBool `json:"hidden,omitempty"`
}

type CrmSchema added in v0.5.0

type CrmSchema struct {
	Labels                     *CrmSchemaLabels        `json:"labels,omitempty"`
	PrimaryDisplayProperty     *HsStr                  `json:"primaryDisplayProperty,omitempty"`
	Archived                   *HsBool                 `json:"archived,omitempty"`
	ID                         *HsStr                  `json:"id,omitempty"`
	FullyQualifiedName         *HsStr                  `json:"fullyQualifiedName,omitempty"`
	CreatedAt                  *HsTime                 `json:"createdAt,omitempty"`
	UpdatedAt                  *HsTime                 `json:"updatedAt,omitempty"`
	ObjectTypeId               *HsStr                  `json:"objectTypeId,omitempty"`
	Properties                 []*CrmProperty          `json:"properties,omitempty"`
	Associations               []*CrmSchemaAssociation `json:"associations,omitempty"`
	Name                       *HsStr                  `json:"name,omitempty"`
	MetaType                   *HsStr                  `json:"metaType,omitempty"`
	RequiredProperties         []*HsStr                `json:"requiredProperties,omitempty"`
	Restorable                 *HsBool                 `json:"restorable,omitempty"`
	SearchableProperties       []*HsStr                `json:"searchableProperties,omitempty"`
	SecondaryDisplayProperties []*HsStr                `json:"secondaryDisplayProperties,omitempty"`
	PortalId                   *HsInt                  `json:"portalId"`
}

type CrmSchemaAssociation added in v0.5.0

type CrmSchemaAssociation struct {
	FromObjectTypeId   *HsStr  `json:"fromObjectTypeId"`
	ToObjectTypeId     *HsStr  `json:"toObjectTypeId"`
	Name               *HsStr  `json:"name"`
	ID                 *HsStr  `json:"id"`
	CreatedAt          *HsTime `json:"createdAt"`
	UpdatedAt          *HsTime `json:"updatedAt"`
	Cardinality        *HsStr  `json:"cardinality"`
	InverseCardinality *HsStr  `json:"inverseCardinality"`
}

type CrmSchemaLabels added in v0.5.0

type CrmSchemaLabels struct {
	Singular *HsStr `json:"singular"`
	Plural   *HsStr `json:"plural"`
}

type CrmSchemasList added in v0.5.0

type CrmSchemasList struct {
	Results []*CrmSchema
}

type CrmSchemasService added in v0.5.0

type CrmSchemasService interface {
	List() (*CrmSchemasList, error)
	Create(reqData interface{}) (*CrmSchema, error)
	Get(objectType string) (*CrmSchema, error)
	Delete(objectType string, option *RequestQueryOption) error
	Update(objectType string, reqData interface{}) (*CrmSchema, error)
}

CrmSchemasService is an interface of CRM schemas endpoints of the HubSpot API. Reference: https://developers.hubspot.com/docs/api/crm/crm-custom-objects

type CrmSchemasServiceOp added in v0.5.0

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

CrmSchemasServiceOp handles communication with the CRM schemas endpoint.

func (*CrmSchemasServiceOp) Create added in v0.5.0

func (s *CrmSchemasServiceOp) Create(reqData interface{}) (*CrmSchema, error)

func (*CrmSchemasServiceOp) Delete added in v0.5.0

func (s *CrmSchemasServiceOp) Delete(objectType string, option *RequestQueryOption) error

func (*CrmSchemasServiceOp) Get added in v0.5.0

func (s *CrmSchemasServiceOp) Get(objectType string) (*CrmSchema, error)

func (*CrmSchemasServiceOp) List added in v0.5.0

func (*CrmSchemasServiceOp) Update added in v0.5.0

func (s *CrmSchemasServiceOp) Update(objectType string, reqData interface{}) (*CrmSchema, error)

type CrmTicket added in v0.6.0

type CrmTicket struct {
	Id                    *HsStr                 `json:"id,omitempty"`
	Properties            map[string]interface{} `json:"properties,omitempty"`
	PropertiesWithHistory map[string]interface{} `json:"propertiesWithHistory,omitempty"`
	CreatedAt             *HsTime                `json:"createdAt,omitempty"`
	UpdatedAt             *HsTime                `json:"updatedAt,omitempty"`
	Archived              *HsBool                `json:"archived,omitempty"`
	ArchivedAt            *HsTime                `json:"archivedAt,omitempty"`
}

type CrmTicketAssociation added in v0.6.0

type CrmTicketAssociation struct {
	To    CrmTicketAssociationTarget `json:"to,omitempty"`
	Types []CrmTicketAssociationType `json:"types,omitempty"`
}

type CrmTicketAssociationTarget added in v0.6.0

type CrmTicketAssociationTarget struct {
	Id *HsStr `json:"id,omitempty"`
}

type CrmTicketAssociationType added in v0.6.0

type CrmTicketAssociationType struct {
	AssociationCategory *HsStr `json:"associationCategory,omitempty"`
	AssociationTypeId   *HsInt `json:"associationTypeId,omitempty"`
}

type CrmTicketCreateRequest added in v0.6.0

type CrmTicketCreateRequest struct {
	Properties   map[string]interface{}  `json:"properties,omitempty"`
	Associations []*CrmTicketAssociation `json:"associations,omitempty"`
}

type CrmTicketSearchFilter added in v0.6.0

type CrmTicketSearchFilter struct {
	Value        *HsStr   `json:"value,omitempty"`
	HighValue    *HsStr   `json:"highValue,omitempty"`
	Values       []*HsStr `json:"values,omitempty"`
	PropertyName *HsStr   `json:"propertyName,omitempty"`
	Operator     *HsStr   `json:"operator,omitempty"`
}

type CrmTicketSearchFilterGroup added in v0.6.0

type CrmTicketSearchFilterGroup struct {
	Filters    []*CrmTicketSearchFilter `json:"filters,omitempty"`
	Sorts      []*HsStr                 `json:"sorts,omitempty"`
	Query      *HsStr                   `json:"query"`
	Properties []*HsStr                 `json:"properties,omitempty"`
	Limit      *HsInt                   `json:"limit,omitempty"`
	After      *HsInt                   `json:"after,omitempty"`
}

type CrmTicketSearchRequest added in v0.6.0

type CrmTicketSearchRequest struct {
	FilterGroups []*CrmTicketSearchFilterGroup `json:"filterGroups,omitempty"`
}

type CrmTicketUpdateRequest added in v0.6.0

type CrmTicketUpdateRequest = CrmTicketCreateRequest

type CrmTicketsList added in v0.6.0

type CrmTicketsList struct {
	Total   *HsInt            `json:"total,omitempty"`
	Results []*CrmTicket      `json:"results"`
	Paging  *CrmTicketsPaging `json:"paging,omitempty"`
}

type CrmTicketsPaging added in v0.6.0

type CrmTicketsPaging struct {
	Next *CrmTicketsPagingData `json:"next,omitempty"`
}

type CrmTicketsPagingData added in v0.6.0

type CrmTicketsPagingData struct {
	After *HsStr `json:"after,omitempty"`
	Link  *HsStr `json:"link,omitempty"`
}

type CrmTicketsService added in v0.10.0

type CrmTicketsService interface {
	List(option *RequestQueryOption) (*CrmTicketsList, error)
	Get(ticketId string, option *RequestQueryOption) (*CrmTicket, error)
	Create(reqData *CrmTicketCreateRequest) (*CrmTicket, error)
	Archive(ticketId string) error
	Update(ticketId string, reqData *CrmTicketUpdateRequest) (*CrmTicket, error)
	Search(reqData *CrmTicketSearchRequest) (*CrmTicketsList, error)
}

CrmTicketsService is an interface of CRM tickets endpoints of the HubSpot API. Reference: https://developers.hubspot.com/docs/api/crm/tickets

type CrmTicketsServiceOp added in v0.10.0

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

CrmTicketsServiceOp handles communication with the CRM tickets endpoints of the HubSpot API.

func (*CrmTicketsServiceOp) Archive added in v0.10.0

func (s *CrmTicketsServiceOp) Archive(ticketId string) error

func (*CrmTicketsServiceOp) Create added in v0.10.0

func (*CrmTicketsServiceOp) Get added in v0.10.0

func (s *CrmTicketsServiceOp) Get(ticketId string, option *RequestQueryOption) (*CrmTicket, error)

func (*CrmTicketsServiceOp) List added in v0.10.0

func (*CrmTicketsServiceOp) Search added in v0.10.0

func (*CrmTicketsServiceOp) Update added in v0.10.0

func (s *CrmTicketsServiceOp) Update(ticketId string, reqData *CrmTicketUpdateRequest) (*CrmTicket, error)

type Deal

type Deal struct {
	Amount                  *HsStr `json:"amount,omitempty"`
	AmountInCompanyCurrency *HsStr `json:"amount_in_home_currency,omitempty"`
	AnnualContractValue     *HsStr `json:"hs_acv,omitempty"`
	AnnualRecurringRevenue  *HsStr `json:"hs_arr,omitempty"`
	ClosedLostReason        *HsStr `json:"closed_lost_reason,omitempty"`
	ClosedWonReason         *HsStr `json:"closed_won_reason,omitempty"`
	DealDescription         *HsStr `json:"description,omitempty"`
	DealName                *HsStr `json:"dealname,omitempty"`
	DealOwnerID             *HsStr `json:"hubspot_owner_id,omitempty"`
	DealStage               *HsStr `json:"dealstage,omitempty"`
	DealType                *HsStr `json:"dealtype,omitempty"`
	ForecastAmount          *HsStr `json:"hs_forecast_amount,omitempty"`
	ForecastCategory        *HsStr `json:"hs_forecast_category,omitempty"`
	ForecastProbability     *HsStr `json:"hs_forecast_probability,omitempty"`
	MonthlyRecurringRevenue *HsStr `json:"hs_mrr,omitempty"`
	NextStep                *HsStr `json:"hs_next_step,omitempty"`
	NumberOfContacts        *HsStr `json:"num_associated_contacts,omitempty"`
	NumberOfSalesActivities *HsStr `json:"num_notes,omitempty"`
	NumberOfTimesContacted  *HsStr `json:"num_contacted_notes,omitempty"`
	ObjectID                *HsStr `json:"hs_object_id,omitempty"`
	PipeLine                *HsStr `json:"pipeline,omitempty"`
	TeamID                  *HsStr `json:"hubspot_team_id,omitempty"`
	TotalContractValue      *HsStr `json:"hs_tcv,omitempty"`

	CreateDate        *HsTime `json:"createdate,omitempty"`
	CloseDate         *HsTime `json:"closedate,omitempty"`
	LastActivityDate  *HsTime `json:"notes_last_updated,omitempty"`
	LastContacted     *HsTime `json:"notes_last_contacted,omitempty"`
	LastModifiedDate  *HsTime `json:"hs_lastmodifieddate,omitempty"`
	NextActivityDate  *HsTime `json:"notes_next_activity_date,omitempty"`
	OwnerAssignedDate *HsTime `json:"hubspot_owner_assigneddate,omitempty"`
}

Deal represents a HubSpot deal.

type DealResponse added in v0.10.0

type DealResponse struct {
	ID         string `json:"id,omitempty"`
	Properties Deal   `json:"properties,omitempty"`
	CreatedAt  string `json:"createdAt,omitempty"`
	UpdatedAt  string `json:"updatedAt,omitempty"`
	Archived   bool   `json:"archived,omitempty"`
}

type DealSearchRequest added in v0.10.0

type DealSearchRequest struct {
	SearchOptions
}

DealSearchRequest represents the request body for searching deals.

type DealSearchResponse added in v0.10.0

type DealSearchResponse struct {
	Total   int            `json:"total,omitempty"`
	Results []DealResponse `json:"results,omitempty"`
}

DealSearchResponse represents the structure of the response from the deal search endpoint.

type DealService

type DealService interface {
	Get(dealID string, deal interface{}, option *RequestQueryOption) (*ResponseResource, error)
	Create(deal interface{}) (*ResponseResource, error)
	Update(dealID string, deal interface{}) (*ResponseResource, error)
	AssociateAnotherObj(dealID string, conf *AssociationConfig) (*ResponseResource, error)
	DeleteAssociation(dealID string, conf *AssociationConfig) error
	SearchByName(dealName string) (*DealSearchResponse, error)
	Search(req *DealSearchRequest) (*DealSearchResponse, error)
}

DealService is an interface of deal endpoints of the HubSpot API. HubSpot deal can be used to manage transactions. It can also be associated with other CRM objects such as contact and company. Reference: https://developers.hubspot.com/docs/api/crm/deals

type DealServiceOp

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

DealServiceOp handles communication with the product related methods of the HubSpot API.

func (*DealServiceOp) AssociateAnotherObj

func (s *DealServiceOp) AssociateAnotherObj(dealID string, conf *AssociationConfig) (*ResponseResource, error)

AssociateAnotherObj associates Deal with another HubSpot objects. If you want to associate a custom object, please use a defined value in HubSpot.

Example
package main

import (
	"fmt"
	"log"
	"os"

	hubspot "github.com/belong-inc/go-hubspot"
)

func main() {
	cli, _ := hubspot.NewClient(hubspot.SetPrivateAppToken(os.Getenv("PRIVATE_APP_TOKEN")))

	res, err := cli.CRM.Deal.AssociateAnotherObj("deal001", &hubspot.AssociationConfig{
		ToObject:   hubspot.ObjectTypeContact,
		ToObjectID: "contact001",
		Type:       hubspot.AssociationTypeDealToContact,
	})
	if err != nil {
		log.Fatal(err)
	}

	r, ok := res.Properties.(*hubspot.Deal)
	if !ok {
		log.Fatal("unable to type assertion")
	}

	// use properties
	_ = r

	fmt.Println(res)

	// // Output:
}

func (*DealServiceOp) Create

func (s *DealServiceOp) Create(deal interface{}) (*ResponseResource, error)

Create creates a new deal. In order to bind the created content, a structure must be specified as an argument. When using custom fields, please embed hubspot.Deal in your own structure.

Example (Apikey)
package main

import (
	"fmt"
	"log"
	"os"

	hubspot "github.com/belong-inc/go-hubspot"
)

type ExampleDeal struct {
	amount  string
	name    string
	stage   string
	ownerID string
}

func main() {
	cli, _ := hubspot.NewClient(hubspot.SetAPIKey(os.Getenv("API_KEY")))

	example := &ExampleDeal{
		amount:  "1500.00",
		name:    "Custom data integrations",
		stage:   "presentation scheduled",
		ownerID: "910901",
	}

	deal := &hubspot.Deal{
		Amount:      hubspot.NewString(example.amount),
		DealName:    hubspot.NewString(example.name),
		DealStage:   hubspot.NewString(example.stage),
		DealOwnerID: hubspot.NewString(example.ownerID),
		PipeLine:    hubspot.NewString("default"),
	}

	res, err := cli.CRM.Deal.Create(deal)
	if err != nil {
		log.Fatal(err)
	}

	r, ok := res.Properties.(*hubspot.Deal)
	if !ok {
		log.Fatal("unable to type assertion")
	}

	// use properties
	_ = r

	fmt.Println(res)

	// // Output:
}
Example (Custom)
package main

import (
	"log"
	"os"

	hubspot "github.com/belong-inc/go-hubspot"
)

type ExampleDeal struct {
	amount  string
	name    string
	stage   string
	ownerID string
}

type CustomDeal struct {
	hubspot.Deal
	CustomA string `json:"custom_a,omitempty"`
	CustomB string `json:"custom_b,omitempty"`
}

func main() {
	cli, _ := hubspot.NewClient(hubspot.SetPrivateAppToken(os.Getenv("PRIVATE_APP_TOKEN")))

	example := &ExampleDeal{
		amount:  "1500.00",
		name:    "Custom data integrations",
		stage:   "presentation scheduled",
		ownerID: "910901",
	}

	// Take advantage of structure embedding when using custom fields.
	deal := &CustomDeal{
		Deal: hubspot.Deal{
			Amount:      hubspot.NewString(example.amount),
			DealName:    hubspot.NewString(example.name),
			DealStage:   hubspot.NewString(example.stage),
			DealOwnerID: hubspot.NewString(example.ownerID),
			PipeLine:    hubspot.NewString("default"),
		},
		CustomA: "custom field A",
		CustomB: "custom field B",
	}

	res, err := cli.CRM.Deal.Create(deal)
	if err != nil {
		log.Fatal(err)
	}

	r, ok := res.Properties.(*CustomDeal)
	if !ok {
		log.Fatal("unable to type assertion")
	}

	// use custom struct
	_ = r

	// // Output:
}
Example (Oauth)
package main

import (
	"fmt"
	"log"

	hubspot "github.com/belong-inc/go-hubspot"
)

type ExampleDeal struct {
	amount  string
	name    string
	stage   string
	ownerID string
}

func main() {
	cli, _ := hubspot.NewClient(hubspot.SetOAuth(&hubspot.OAuthConfig{
		GrantType:    hubspot.GrantTypeRefreshToken,
		ClientID:     "hubspot-client-id",
		ClientSecret: "hubspot-client-secret",
		RefreshToken: "hubspot-refresh-token",
	}))

	example := &ExampleDeal{
		amount:  "1500.00",
		name:    "Custom data integrations",
		stage:   "presentation scheduled",
		ownerID: "910901",
	}

	deal := &hubspot.Deal{
		Amount:      hubspot.NewString(example.amount),
		DealName:    hubspot.NewString(example.name),
		DealStage:   hubspot.NewString(example.stage),
		DealOwnerID: hubspot.NewString(example.ownerID),
		PipeLine:    hubspot.NewString("default"),
	}

	res, err := cli.CRM.Deal.Create(deal)
	if err != nil {
		log.Fatal(err)
	}

	r, ok := res.Properties.(*hubspot.Deal)
	if !ok {
		log.Fatal("unable to type assertion")
	}

	// use properties
	_ = r

	fmt.Println(res)

	// // Output:
}
Example (Privateapp)
package main

import (
	"fmt"
	"log"
	"os"

	hubspot "github.com/belong-inc/go-hubspot"
)

type ExampleDeal struct {
	amount  string
	name    string
	stage   string
	ownerID string
}

func main() {
	cli, _ := hubspot.NewClient(hubspot.SetPrivateAppToken(os.Getenv("PRIVATE_APP_TOKEN")))

	example := &ExampleDeal{
		amount:  "1500.00",
		name:    "Custom data integrations",
		stage:   "presentation scheduled",
		ownerID: "910901",
	}

	deal := &hubspot.Deal{
		Amount:      hubspot.NewString(example.amount),
		DealName:    hubspot.NewString(example.name),
		DealStage:   hubspot.NewString(example.stage),
		DealOwnerID: hubspot.NewString(example.ownerID),
		PipeLine:    hubspot.NewString("default"),
	}

	res, err := cli.CRM.Deal.Create(deal)
	if err != nil {
		log.Fatal(err)
	}

	r, ok := res.Properties.(*hubspot.Deal)
	if !ok {
		log.Fatal("unable to type assertion")
	}

	// use properties
	_ = r

	fmt.Println(res)

	// // Output:
}

func (*DealServiceOp) DeleteAssociation added in v0.11.0

func (s *DealServiceOp) DeleteAssociation(dealID string, conf *AssociationConfig) error

DeleteAssociation removes an association between Deal and another HubSpot object. It is the inverse of AssociateAnotherObj.

func (*DealServiceOp) Get

func (s *DealServiceOp) Get(dealID string, deal interface{}, option *RequestQueryOption) (*ResponseResource, error)

Get gets a deal. In order to bind the get content, a structure must be specified as an argument. Also, if you want to get a custom field, you need to specify the field name. If you specify a non-existent field, it will be ignored. e.g. &hubspot.RequestQueryOption{ Properties: []string{"custom_a", "custom_b"}}

Example
package main

import (
	"fmt"
	"log"
	"os"

	hubspot "github.com/belong-inc/go-hubspot"
)

func main() {
	cli, _ := hubspot.NewClient(hubspot.SetPrivateAppToken(os.Getenv("PRIVATE_APP_TOKEN")))

	res, err := cli.CRM.Deal.Get("deal001", &hubspot.Deal{}, nil)
	if err != nil {
		log.Fatal(err)
	}

	r, ok := res.Properties.(*hubspot.Deal)
	if !ok {
		log.Fatal("unable to type assertion")
	}

	// use properties
	_ = r

	fmt.Println(res)

	// // Output:
}
Example (Custom)
package main

import (
	"fmt"
	"log"
	"os"

	hubspot "github.com/belong-inc/go-hubspot"
)

type CustomDeal struct {
	hubspot.Deal
	CustomA string `json:"custom_a,omitempty"`
	CustomB string `json:"custom_b,omitempty"`
}

func main() {
	cli, _ := hubspot.NewClient(hubspot.SetPrivateAppToken(os.Getenv("PRIVATE_APP_TOKEN")))

	res, err := cli.CRM.Deal.Get("deal001", &CustomDeal{}, &hubspot.RequestQueryOption{
		CustomProperties: []string{
			"custom_a",
			"custom_b",
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	r, ok := res.Properties.(*CustomDeal)
	if !ok {
		log.Fatal("unable to type assertion")
	}

	// use properties
	_ = r

	fmt.Println(res)

	// // Output:
}

func (*DealServiceOp) Search added in v0.10.0

Search searches for deals based on the provided search request. EXPERIMENTAL: This method is experimental and the interface may change in the future to support custom properties.

func (*DealServiceOp) SearchByName added in v0.10.0

func (s *DealServiceOp) SearchByName(dealName string) (*DealSearchResponse, error)

SearchByName searches for deals by deal name. EXPERIMENTAL: This method is experimental and the interface may change in the future to support custom properties.

func (*DealServiceOp) Update

func (s *DealServiceOp) Update(dealID string, deal interface{}) (*ResponseResource, error)

Update updates a deal. In order to bind the updated content, a structure must be specified as an argument. When using custom fields, please embed hubspot.Deal in your own structure.

Example
package main

import (
	"fmt"
	"log"
	"os"

	hubspot "github.com/belong-inc/go-hubspot"
)

type ExampleDeal struct {
	amount  string
	name    string
	stage   string
	ownerID string
}

func main() {
	cli, _ := hubspot.NewClient(hubspot.SetPrivateAppToken(os.Getenv("PRIVATE_APP_TOKEN")))

	example := &ExampleDeal{
		amount:  "1500.00",
		name:    "Custom data integrations",
		stage:   "presentation scheduled",
		ownerID: "910901",
	}

	deal := &hubspot.Deal{
		Amount:      hubspot.NewString(example.amount),
		DealName:    hubspot.NewString(example.name),
		DealStage:   hubspot.NewString(example.stage),
		DealOwnerID: hubspot.NewString(example.ownerID),
		PipeLine:    hubspot.NewString("default"),
	}

	res, err := cli.CRM.Deal.Update("deal001", deal)
	if err != nil {
		log.Fatal(err)
	}

	r, ok := res.Properties.(*hubspot.Deal)
	if !ok {
		log.Fatal("unable to type assertion")
	}

	// use properties
	_ = r

	fmt.Println(res)

	// // Output:
}

type ErrContext

type ErrContext struct {
	ID             []string `json:"id,omitempty"`
	Type           []string `json:"type,omitempty"`
	ObjectType     []string `json:"objectType,omitempty"`
	FromObjectType []string `json:"fromObjectType,omitempty"`
	ToObjectType   []string `json:"toObjectType,omitempty"`
}

type ErrDetail

type ErrDetail struct {
	IsValid bool   `json:"isValid,omitempty"`
	Message string `json:"message,omitempty"`
	Error   string `json:"error,omitempty"`
	Name    string `json:"name,omitempty"`
}
type ErrLinks struct {
	APIKey        string `json:"api key,omitempty"`
	KnowledgeBase string `json:"knowledge-base,omitempty"`
}

type Filter added in v0.10.0

type Filter struct {
	PropertyName string   `json:"propertyName"`
	Operator     Operator `json:"operator"`
	Values       []HsStr  `json:"values,omitempty"`
	Value        *HsStr   `json:"value,omitempty"`
	HighValue    *HsStr   `json:"highValue,omitempty"`
}

Filter represents a single filter for HubSpot search requests.

type FilterGroup added in v0.10.0

type FilterGroup struct {
	Filters []Filter `json:"filters,omitempty"`
}

FilterGroup represents a group of filters for HubSpot search requests.

type HsBool

type HsBool bool

HsBool is defined to marshal the HubSpot boolean fields of `true`, `"true"`, and so on, into a bool type.

func NewBoolean added in v0.9.0

func NewBoolean(b bool) *HsBool

NewBoolean returns pointer HsBool(bool)

func (*HsBool) UnmarshalJSON

func (hb *HsBool) UnmarshalJSON(b []byte) error

UnmarshalJSON implemented json.Unmarshaler. This is because there are cases where the Time value returned by HubSpot is null or "true" / "false".

type HsInt added in v0.5.0

type HsInt int

func NewInt added in v0.5.0

func NewInt(v int) *HsInt

func (*HsInt) String added in v0.8.0

func (hi *HsInt) String() string

String implemented Stringer.

func (*HsInt) UnmarshalJSON added in v0.8.0

func (hi *HsInt) UnmarshalJSON(b []byte) error

UnmarshalJSON implemented json.Unmarshaler. This is because there are cases where the Int value returned by HubSpot is "" or "12345".

type HsStr

type HsStr string

HsStr is defined to identify HubSpot's empty string from null. If you want to set a HubSpot's value, use NewString(), if null, use `nil` in the request field.

func NewString

func NewString(s string) *HsStr

NewString returns pointer HsStr(string). Make sure to use BlankStr for empty string.

func (*HsStr) String

func (hs *HsStr) String() string

String implemented Stringer.

type HsTime

type HsTime time.Time

HsTime is defined to identify HubSpot time fields with null and empty string. If you want to set a HubSpot's value, use NewTime(), if null, use `nil` in the request field.

func NewTime added in v0.1.1

func NewTime(t time.Time) *HsTime

NewTime returns pointer HsTime(time.Time).

func (*HsTime) String

func (ht *HsTime) String() string

String implemented Stringer.

func (*HsTime) ToTime

func (ht *HsTime) ToTime() *time.Time

ToTime convert HsTime to time.Time. If the value is zero, it will be return nil.

func (*HsTime) UnmarshalJSON

func (ht *HsTime) UnmarshalJSON(b []byte) error

UnmarshalJSON implemented json.Unmarshaler. This is because there are cases where the Time value returned by HubSpot is null or empty string. The time.Time does not support Parse with empty string. Supports both unix timestamps (milliseconds) and ISO 8601 date strings.

type IdentificationTokenRequest added in v0.8.0

type IdentificationTokenRequest struct {
	FirstName string `json:"firstName"`
	LastName  string `json:"lastName"`
	Email     string `json:"email"`
}

type IdentificationTokenResponse added in v0.8.0

type IdentificationTokenResponse struct {
	Token string `json:"token"`
}

type Marketing added in v0.2.0

type Marketing struct {
	Email         MarketingEmailService
	Transactional TransactionalService
}

type MarketingEmailOp added in v0.2.0

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

func (*MarketingEmailOp) GetStatistics added in v0.2.0

func (m *MarketingEmailOp) GetStatistics(emailID int, resource interface{}) (*ResponseResource, error)

GetStatistics get a Statistics for given emailID.

Example
package main

import (
	"fmt"
	"log"
	"os"

	hubspot "github.com/belong-inc/go-hubspot"
)

func main() {
	cli, _ := hubspot.NewClient(hubspot.SetPrivateAppToken(os.Getenv("PRIVATE_APP_TOKEN")))

	emailID := 0 // Set proper value.
	res, err := cli.Marketing.Email.GetStatistics(emailID, &hubspot.Statistics{})
	if err != nil {
		log.Fatal(err)
	}

	r, ok := res.Properties.(*hubspot.Statistics)
	if !ok {
		log.Fatal("unable to type assertion")
	}

	// use properties
	_ = r

	fmt.Printf("%+v", r)

	// // Output:
}

func (*MarketingEmailOp) ListStatistics added in v0.2.0

func (m *MarketingEmailOp) ListStatistics(resource interface{}, option *BulkRequestQueryOption) (*ResponseResource, error)

ListStatistics get a list of Statistics.

Example
package main

import (
	"fmt"
	"log"
	"os"

	hubspot "github.com/belong-inc/go-hubspot"
)

func main() {
	cli, _ := hubspot.NewClient(hubspot.SetPrivateAppToken(os.Getenv("PRIVATE_APP_TOKEN")))

	statistics := make([]hubspot.Statistics, 0, 50)
	res, err := cli.Marketing.Email.ListStatistics(&hubspot.BulkStatisticsResponse{Objects: statistics}, &hubspot.BulkRequestQueryOption{Limit: 10})
	if err != nil {
		log.Fatal(err)
	}

	r, ok := res.Properties.(*hubspot.BulkStatisticsResponse)
	if !ok {
		log.Fatal("unable to type assertion")
	}

	// use properties
	_ = r

	fmt.Printf("%+v", r)

	// // Output:
}

type MarketingEmailService added in v0.2.0

type MarketingEmailService interface {
	GetStatistics(emailID int, statistics interface{}) (*ResponseResource, error)
	ListStatistics(statistics interface{}, option *BulkRequestQueryOption) (*ResponseResource, error)
}

MarketingEmailService is an interface of marketing email endpoints of the HubSpot API. As of May 2022, HubSpot provides only API v1 therefore the implementation is based on document in https://legacydocs.hubspot.com/docs/methods/cms_email/get-the-statistics-for-a-marketing-email.

func NewMarketingEmail added in v0.2.0

func NewMarketingEmail(client *Client) MarketingEmailService

NewMarketingEmail creates a new MarketingEmailService.

type Note added in v0.10.0

type Note struct {
	HsCreateDate   *HsTime `json:"hs_createdate,omitempty"`
	HsObjectID     *HsStr  `json:"hs_object_id,omitempty"`
	HsNoteBody     *HsStr  `json:"hs_note_body,omitempty"`
	HsTimestamp    *HsStr  `json:"hs_timestamp,omitempty"`
	HubspotOwnerID *HsStr  `json:"hubspot_owner_id,omitempty"`
}

Note represents a note in HubSpot.

type NoteService added in v0.10.0

type NoteService interface {
	Get(noteID string, note interface{}, option *RequestQueryOption) (*ResponseResource, error)
	Create(note interface{}) (*ResponseResource, error)
	Update(noteID string, note interface{}) (*ResponseResource, error)
	Delete(noteID string) error
	AssociateAnotherObj(noteID string, conf *AssociationConfig) (*ResponseResource, error)
	DeleteAssociation(noteID string, conf *AssociationConfig) error
}

NoteService is an interface of note endpoints of the HubSpot API. HubSpot notes store information about interactions and communications. It can be associated with other CRM objects such as contact, company, and deal. Reference: https://developers.hubspot.com/docs/api/crm/notes

type NoteServiceOp added in v0.10.0

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

NoteServiceOp handles communication with the note related methods of the HubSpot API.

func (*NoteServiceOp) AssociateAnotherObj added in v0.10.0

func (s *NoteServiceOp) AssociateAnotherObj(noteID string, conf *AssociationConfig) (*ResponseResource, error)

AssociateAnotherObj associates Note with another HubSpot objects. If you want to associate a custom object, please use a defined value in HubSpot.

func (*NoteServiceOp) Create added in v0.10.0

func (s *NoteServiceOp) Create(note interface{}) (*ResponseResource, error)

Create creates a new note. In order to bind the created content, a structure must be specified as an argument. When using custom fields, please embed hubspot.Note in your own structure.

func (*NoteServiceOp) Delete added in v0.10.0

func (s *NoteServiceOp) Delete(noteID string) error

Delete deletes a note.

func (*NoteServiceOp) DeleteAssociation added in v0.11.0

func (s *NoteServiceOp) DeleteAssociation(noteID string, conf *AssociationConfig) error

DeleteAssociation removes an association between Note and another HubSpot object. It is the inverse of AssociateAnotherObj.

func (*NoteServiceOp) Get added in v0.10.0

func (s *NoteServiceOp) Get(noteID string, note interface{}, option *RequestQueryOption) (*ResponseResource, error)

Get gets a note. In order to bind the get content, a structure must be specified as an argument. Also, if you want to gets a custom field, you need to specify the field name. If you specify a non-existent field, it will be ignored. e.g. &hubspot.RequestQueryOption{ Properties: []string{"custom_a", "custom_b"}}

func (*NoteServiceOp) Update added in v0.10.0

func (s *NoteServiceOp) Update(noteID string, note interface{}) (*ResponseResource, error)

Update updates a note. In order to bind the updated content, a structure must be specified as an argument. When using custom fields, please embed hubspot.Note in your own structure.

type OAuth

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

func (*OAuth) SetAuthentication

func (o *OAuth) SetAuthentication(r *http.Request) error

type OAuthConfig

type OAuthConfig struct {
	GrantType    string `json:"grant_type"`
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
	RefreshToken string `json:"refresh_token"`
}

type OAuthToken

type OAuthToken struct {
	AccessToken  string    `json:"access_token"`
	RefreshToken string    `json:"refresh_token"`
	ExpiresIn    int       `json:"expires_in"`
	Expiry       time.Time `json:"-"`
}

type OAuthTokenManager

type OAuthTokenManager struct {
	HTTPClient *http.Client
	Config     *OAuthConfig
	Token      *OAuthToken
	// contains filtered or unexported fields
}

func (*OAuthTokenManager) RetrieveToken

func (otm *OAuthTokenManager) RetrieveToken() (*OAuthToken, error)

type OAuthTokenRetriever

type OAuthTokenRetriever interface {
	RetrieveToken() (*OAuthToken, error)
}

type ObjectType

type ObjectType string

ObjectType is the name used in object association.

const (
	ObjectTypeContact ObjectType = "contacts"
	ObjectTypeDeal    ObjectType = "deals"
	ObjectTypeCompany ObjectType = "company"
)

Default Object types

type Operator added in v0.10.0

type Operator string

Operator is search for HubSpot API filters. It defines the operators that can be used in search filters for various HubSpot objects such as contacts, companies, deals, and tickets. https://developers.hubspot.com/docs/guides/api/crm/search#filter-search-results

const (
	LT               Operator = "LT"                 // Less than the specified value.
	LTE              Operator = "LTE"                // Less than or equal to the specified value.
	GT               Operator = "GT"                 // Greater than the specified value.
	GTE              Operator = "GTE"                // Greater than or equal to the specified value.
	EQ               Operator = "EQ"                 // Equal to the specified value.
	NEQ              Operator = "NEQ"                // Not equal to the specified value.
	Between          Operator = "BETWEEN"            // Within the specified range. In your request, use key-value pairs to set highValue and value. Refer to the example below the table.
	IN               Operator = "IN"                 // Included within the specified list. Searches by exact match. In your request, include the list values in a values array. When searching a string property with this operator, values must be lowercase. Refer to the example below the table.
	NotIN            Operator = "NOT_IN"             // Not included within the specified list. In your request, include the list values in a values array. When searching a string property with this operator, values must be lowercase.
	HasProperty      Operator = "HAS_PROPERTY"       // Has a value for the specified property.
	NotHasProperty   Operator = "NOT_HAS_PROPERTY"   // Doesn't have a value for the specified property.
	ContainsToken    Operator = "CONTAINS_TOKEN"     // Contains a token. In your request, you can use wildcards (*) to complete a partial search. For example, use the value *@hubspot.com to retrieve contacts with a HubSpot email address.
	NotContainsToken Operator = "NOT_CONTAINS_TOKEN" // Doesn't contain a token.
)

type Option

type Option func(c *Client)

func WithAPIVersion

func WithAPIVersion(version string) Option

func WithBaseURL

func WithBaseURL(url *url.URL) Option

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

type PrivateAppToken added in v0.3.0

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

func (*PrivateAppToken) SetAuthentication added in v0.3.0

func (p *PrivateAppToken) SetAuthentication(r *http.Request) error

type RequestPayload

type RequestPayload struct {
	Properties interface{} `json:"properties,omitempty"`
}

RequestPayload is common request structure for HubSpot APIs.

type RequestQueryOption

type RequestQueryOption struct {
	Properties           []string `url:"properties,comma,omitempty"`
	CustomProperties     []string `url:"-"`
	Associations         []string `url:"associations,comma,omitempty"`
	PaginateAssociations bool     `url:"paginateAssociations,omitempty"` // HubSpot defaults false
	Archived             bool     `url:"archived,omitempty"`             // HubSpot defaults false
	IDProperty           string   `url:"idProperty,omitempty"`
}

RequestQueryOption is a set of options to be specified in the query when making a Get request. RequestQueryOption.Properties will be overwritten internally, so do not specify it. If you want to get the custom fields as well, specify the field names in RequestQueryOption.CustomProperties. Items with no value set will be ignored.

type ResponseResource

type ResponseResource struct {
	ID           string        `json:"id,omitempty"`
	Archived     bool          `json:"archived,omitempty"`
	Associations *Associations `json:"associations,omitempty"`
	Properties   interface{}   `json:"properties,omitempty"`
	CreatedAt    *HsTime       `json:"createdAt,omitempty"`
	UpdatedAt    *HsTime       `json:"updatedAt,omitempty"`
	ArchivedAt   *HsTime       `json:"archivedAt,omitempty"`
}

ResponseResource is common response structure for HubSpot APIs.

type SearchOptions added in v0.10.0

type SearchOptions struct {
	FilterGroups []FilterGroup `json:"filterGroups,omitempty"` // A list of filter groups, each containing one or more filters.
	Sorts        []Sort        `json:"sorts,omitempty"`
	Query        string        `json:"query,omitempty"`
	Properties   []string      `json:"properties,omitempty"`
	Limit        int           `json:"limit,omitempty"` // The maximum number of entries per page is 200, the default is 10.
	After        int           `json:"after,omitempty"` // The offset for pagination, used to retrieve the next page of results.
}

SearchOptions represents the options for searching HubSpot objects.

type SendSingleEmailMessage added in v0.4.0

type SendSingleEmailMessage struct {
	To      string   `json:"to"`
	From    string   `json:"from,omitempty"`
	SendId  string   `json:"sendId,omitempty"`
	ReplyTo []string `json:"replyTo,omitempty"`
	Cc      []string `json:"cc,omitempty"`
	Bcc     []string `json:"bcc,omitempty"`
}

type SendSingleEmailProperties added in v0.4.0

type SendSingleEmailProperties struct {
	EmailId           int64                   `json:"emailId"`
	Message           *SendSingleEmailMessage `json:"message"`
	ContactProperties *Contact                `json:"contactProperties,omitempty"`
	CustomProperties  interface{}             `json:"customProperties,omitempty"`
}

type SendSingleEmailResponse added in v0.4.0

type SendSingleEmailResponse struct {
	RequestedAt string `json:"requestedAt"`
	StatusId    string `json:"statusId"`
	Status      string `json:"status"`
}

type Sort added in v0.10.0

type Sort struct {
	PropertyName string        `json:"propertyName"`
	Direction    SortDirection `json:"direction"`
}

type SortDirection added in v0.10.0

type SortDirection string
const (
	Asc  SortDirection = "ASCENDING"
	Desc SortDirection = "DESCENDING"
)

type Statistics added in v0.2.0

type Statistics = legacy.StatisticsResponse

Statistics is response from marketing email statistics API v1 as of now.

type TransactionalService added in v0.4.0

type TransactionalService interface {
	SendSingleEmail(props *SendSingleEmailProperties) (*SendSingleEmailResponse, error)
}

TransactionalService is an interface for the marketing/transactional service of the HubSpot API. Reference: https://developers.hubspot.com/docs/api/marketing/transactional-emails

type TransactionalServiceOp added in v0.4.0

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

TransactionalServiceOp provides the default implementation of TransactionService.

func (*TransactionalServiceOp) SendSingleEmail added in v0.4.0

Example
package main

import (
	"fmt"
	"log"
	"os"

	hubspot "github.com/belong-inc/go-hubspot"
)

func main() {
	cli, _ := hubspot.NewClient(hubspot.SetPrivateAppToken(os.Getenv("PRIVATE_APP_TOKEN")))

	res, err := cli.Marketing.Transactional.SendSingleEmail(&hubspot.SendSingleEmailProperties{
		EmailId: 0, // Set proper value.
		Message: &hubspot.SendSingleEmailMessage{
			To:      "to@example.com",
			From:    "from@example.com",
			SendId:  "SEND_ID",
			ReplyTo: []string{"reply@example.com"},
			Cc:      []string{"cc@example.com"},
			Bcc:     []string{"bcc@example.com"},
		},
		ContactProperties: &hubspot.Contact{
			FirstName:   hubspot.NewString("Bryan"),
			LastName:    hubspot.NewString("Cooper"),
			Email:       hubspot.NewString("hubspot@example.com"),
			MobilePhone: hubspot.NewString("(877) 929-0687"),
			Zip:         hubspot.NewString("1000001"),
		},
		CustomProperties: map[string]string{
			"custom_email":     "hubspot@example.com",
			"custom_firstname": "Bryan",
			"custom_lastname":  "Cooper",
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%+v", res)

	// // Output:
}

type VisitorIdentificationService added in v0.8.0

type VisitorIdentificationService interface {
	GenerateIdentificationToken(option IdentificationTokenRequest) (*IdentificationTokenResponse, error)
}

type VisitorIdentificationServiceOp added in v0.8.0

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

func (*VisitorIdentificationServiceOp) GenerateIdentificationToken added in v0.8.0

Directories

Path Synopsis
Package legacy is the package for legacy APIs in Hubspot.
Package legacy is the package for legacy APIs in Hubspot.
tools module

Jump to

Keyboard shortcuts

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