whatsapp

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 18, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package whatsapp provides a client and utilities for interacting with the WhatsApp Business API.

Package whatsapp provides client functionalities to interact with the WhatsApp API.

Index

Constants

View Source
const (
	OGGExtension            = ".ogg"
	OpusExtension           = ".opus"
	AACExtension            = ".aac"
	DefaultAudioExtension   = OpusExtension
	DefaultVideoExtension   = MP4Extension
	DefaultImageExtension   = JPEGExtension
	DefaultStickerExtension = WebpExtension
	MP4Extension            = ".mp4"
	JPEGExtension           = ".jpeg"
	InvalidImgExtension     = ".jfif"
	ZipExtension            = ".zip"
	RarExtension            = ".rar"
	DocxExtension           = ".docx"
	XlsxExtension           = ".xlsx"
	PptxExtension           = ".pptx"
	WebpExtension           = ".webp"
	CSVExtension            = ".csv"
	VCFExtension            = ".vcf"
	TextExtension           = ".txt"
	DefaultContentType      = "application/octet-stream"
)

Standard file extensions and default content types used within the package.

View Source
const BaseUrl = meta.GraphAPIBaseUrl

BaseUrl represents the default Graph API base URL used by the client.

View Source
const DefaultRetryDuration time.Duration = 2 * time.Second

DefaultRetryDuration represents the default duration of type time.Duration to wait between retry attempts.

Variables

View Source
var ErrAtLeastOneButtonRequired = errors.New("at least one button is required")

ErrAtLeastOneButtonRequired is returned when trying to send an interactive message without buttons.

View Source
var ErrCannotGetCallId = errors.New("cannot get call id")

ErrCannotGetCallId is returned when the call ID cannot be parsed or retrieved from the InviteCallResponse.

View Source
var ErrInvalidContactName = errors.New("invalid contact name")

ErrInvalidContactName is returned when the contact name does not contain at least a first and last name.

View Source
var ErrInvalidFile = errors.New("invalid file")

ErrInvalidFile is returned when the content type of the provided file bytes cannot be properly detected or resolves to the default content type.

View Source
var ErrInvalidMimeType = errors.New("invalid mimeType")

ErrInvalidMimeType indicates that the provided MIME type is not supported for media uploads.

View Source
var ErrMessageNotSent = errors.New("message not sent")

ErrMessageNotSent is returned when the API response does not contain a valid message ID.

View Source
var ErrMissingMediaID = errors.New("media upload returned no id")

ErrMissingMediaID indicates that the upload response decoded successfully but contained no media ID, which happens when the Graph API returns an error envelope with a 2xx status code.

View Source
var ErrTooManyButtons = errors.New("a maximum of 3 quick reply buttons is allowed")

ErrTooManyButtons is returned when more than the Meta-allowed number of quick reply buttons (3) is provided.

View Source
var ErrUnsupportedLanguage = errors.New("unsupported language for time layout")

ErrUnsupportedLanguage is returned when the provided Lang has no mapped TimeLayout.

Functions

func Approved added in v0.0.6

func Approved() status

Approved returns a [status] indicating that the template has been approved.

func Aproved deprecated

func Aproved() status

Aproved returns a [status] indicating that the template has been approved.

Deprecated: Aproved is misspelled; use Approved instead.

func ContentTypes

func ContentTypes(
	audioType,
	videoType,
	imageType,
	stickerType string,
) map[string]string

ContentTypes returns a map associating standard MIME types with their corresponding MessageType string representations.

func CreateMessageTemplate

func CreateMessageTemplate(
	api *Client,
	field TemplateFields,
) error

CreateMessageTemplate performs an HTTP POST request to the Meta API to create a new message template. It uses the Client configuration and the provided TemplateFields to build the request body.

func DeleteMessageTemplate

func DeleteMessageTemplate(api *Client, name string) error

func DescribeDate

func DescribeDate(date, now time.Time, lang Lang) (string, string)

DescribeDate returns a localized relative day description or the exact date fallback, along with the formatted hour string, based on the time.Time and Lang.

func GenerateFileName

func GenerateFileName(fileName string) string

GenerateFileName creates a new unique file name by generating a UUID using uuid.NewV7 and appending the extension from the original fileName.

func GenerateWhatsappLink(phone, text string) string

GenerateWhatsappLink creates a direct WhatsApp API link with the provided phone number and URL-escaped text.

func IsBSUID added in v1.0.0

func IsBSUID(identifier string) bool

IsBSUID reports whether identifier follows the BSUID format. Phone numbers, which contain only digits and an optional leading "+", never match, so the distinction between a recipient phone number and a BSUID is unambiguous.

func IsValidMediaUploadType

func IsValidMediaUploadType(mimeType string) bool

IsValidMediaUploadType reports whether mimeType is accepted by the WhatsApp Cloud API for media uploads.

  • It matches the exact canonical MIME types from Meta's supported-media-types specification: images (jpeg, png, webp), videos (mp4, 3gpp), audio (aac, mp4, amr, mpeg, ogg) and documents (txt, pdf, doc/docx, xls/xlsx, ppt/pptx).
  • Callers should normalize the MIME type via NormalizeMediaMimeType first; this function performs only the final allowlist check.

func IsValidProfileVertical

func IsValidProfileVertical(v string) bool

IsValidProfileVertical checks whether the provided string v corresponds to a supported ProfileVertical.

  • It returns true if it is a valid vertical, or false otherwise.

func MarkMessageAsRead

func MarkMessageAsRead(
	api *Client,
	messageID string,
) error

MarkMessageAsRead sends a request using the provided Client to update the message status to read.

func MimeTypeWithMessageType

func MimeTypeWithMessageType(messageType MessageType) string

MimeTypeWithMessageType returns the default MIME type string for a specific MessageType. It utilizes mime.TypeByExtension to determine the MIME type based on default extensions. If the MessageType does not match a known type, it returns DefaultContentType.

func NormalizeDate

func NormalizeDate(date time.Time) time.Time

NormalizeDate resets the time components of a time.Time to midnight, keeping the location intact.

func NormalizeMediaMimeType added in v0.0.4

func NormalizeMediaMimeType(mimeType, filePath string, content []byte) string

NormalizeMediaMimeType resolves a possibly generic, mobile-specific, or ffmpeg-mangled MIME type into a canonical MIME type accepted by the WhatsApp Cloud API. It combines three strategies, in order of reliability:

  1. File extension of filePath (most reliable for mobile audio and OOXML documents whose MIME type is frequently generic).
  2. Magic-byte sniffing of content for generic/empty inputs.
  3. Category-based correction of inputs that are valid in shape but use a codec-specific or platform variant Meta does not accept.

When no strategy yields a known-good type, the original (trimmed, lower-cased) MIME type is returned so the caller can still surface a meaningful error.

func Pending

func Pending() status

Pending returns a [status] indicating that the template is pending approval.

func Rejected

func Rejected() status

Rejected returns a [status] indicating that the template has been rejected.

func Retry

func Retry(
	ctx context.Context,
	maxRetries int,
	duration time.Duration,
	fn func() error,
) (int, error)

Retry executes the provided function up to maxRetries times.

  • It waits for the specified time.Duration between attempts.
  • It returns the number of failed attempts and the last error encountered.
  • It respects the context.Context for cancellation, stopping immediately if the context is done.

func ScheduleUrls

func ScheduleUrls(cancel, reschedule string) scheduleUrls

ScheduleUrls creates and returns a new [scheduleUrls].

func SetRecipient added in v1.0.0

func SetRecipient(payload xjson.JSON, identifier string)

SetRecipient writes identifier to the correct WhatsApp payload field. A BSUID is assigned to "recipient"; any other value is treated as a phone number and assigned to "to". Callers that already pass phone numbers keep an identical payload, so existing integrations require no changes.

func TypingIndicator

func TypingIndicator(
	api *Client,
	messageId string,
) error

TypingIndicator sends a request to the WhatsApp Messages API to mark a specific message as read and display a typing indicator to the user.

The typing indicator informs the user that a response is being prepared, which is a best practice when the response takes a few seconds to be generated.

The indicator is automatically removed after a reply is sent or after 25 seconds, whichever occurs first. It should only be triggered if a response is intended to be sent to avoid a poor user experience.

Parameters:

  • api: Client The WhatsApp API client instance.
  • messageId: [string] The unique ID of the message to be marked as read.

func WebhookSubscribe

func WebhookSubscribe(
	whats *Client,
	wabaId string,
	pin WebhookPin,
) error

WebhookSubscribe registers the sender and subscribes the application to the specified WhatsApp Business Account (wabaId).

  • It uses the provided Client to perform the requests and requires a WebhookPin containing the registration and subscription 2FA pins.

Types

type CMessageTemplate

type CMessageTemplate struct {
	Name                string       `json:"name"`
	Language            Lang         `json:"language"`
	Category            Category     `json:"category"`
	AllowCategoryChange bool         `json:"allow_category_change"`
	Components          []xjson.JSON `json:"components"`
}

CMessageTemplate represents the request structure used to create a new message template on the Meta platform.

type Call

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

Call represents a WhatsApp calling API handler. It uses a Client to communicate with the API and an EventEmitter for real-time events.

func NewCall

func NewCall(
	c *Client,
	appId string,
	eventEmitter EventEmitter,
	logger ...func(message string),
) *Call

NewCall creates and returns a new Call instance. It requires a Client, an application ID, an EventEmitter, and an optional logger function.

func (*Call) AcceptCall

func (c *Call) AcceptCall(id, answerSdp string) string

AcceptCall accepts an incoming call using the provided ID and answer SDP. It sends an accept action payload formatted as xjson.JSON through the Client.

func (*Call) InitiateOutboundCall

func (c *Call) InitiateOutboundCall(phoneNumber, offerSdp string) (InitCall, error)

InitiateOutboundCall starts a new outbound call to the specified phone number using the provided offer SDP. It returns an InitCall or an error if the request fails.

func (*Call) WebhookPreAccept

func (c *Call) WebhookPreAccept(id string, data CallData, sdpPayload string)

WebhookPreAccept processes webhook events using the provided CallData to determine the call status. It handles pre-accepting incoming calls, answering outbound calls, and notifying when calls end or are canceled via the EventEmitter.

type CallData

type CallData struct {
	Status string `json:"status"`
}

CallData holds the status information of a call event.

type Category

type Category string

Category defines the classification of the message template according to Meta's requirements.

const (
	// MARKETING templates include promotional offers, product announcements, and more.
	MARKETING Category = "MARKETING"
	// UTILITY templates facilitate a specific, agreed-upon transaction or update.
	UTILITY Category = "UTILITY"
	// AUTHENTICATION templates enable businesses to authenticate users with one-time passcodes.
	AUTHENTICATION Category = "AUTHENTICATION"
)

type Clicked

type Clicked struct {
	ButtonContent string `json:"button_content"`
	Count         int    `json:"count"`
	Type          string `json:"type"`
}

Clicked contains interaction details for template buttons.

type Client

type Client struct {
	meta.GraphAPIClient
	// contains filtered or unexported fields
}

Client represents the WhatsApp API client. It encapsulates the sender ID and inherits from meta.GraphAPIClient to handle API requests.

func Default

func Default(senderId, accessToken string) *Client

Default creates and returns a new Client with the provided senderId and accessToken, using a background context.Context and the default Graph API version.

func New

func New(
	ctx context.Context,
	apiVersion,
	accessToken,
	senderID string,
) *Client

New creates and returns a new Client with the specified context.Context, API version, access token, and sender ID.

func (*Client) ChangeSenderId

func (c *Client) ChangeSenderId(id string)

ChangeSenderId updates the sender ID of the Client to the provided id.

func (*Client) Endpoint

func (c *Client) Endpoint(endpoint string) string

Endpoint constructs and returns the full API URL string for a given endpoint.

func (*Client) GenerateMediaID

func (api *Client) GenerateMediaID(
	mimeType string,
	filePath string,
	fileBytes io.Reader,
) (string, error)

GenerateMediaID uploads a media file to the WhatsApp API and returns its ID.

  • It reads the file data from an io.Reader, constructs the multipart form, and sends an HTTP POST request configured with xhttp.Options.
  • The provided mimeType is normalized via NormalizeMediaMimeType before validation, so generic (application/octet-stream), mobile-specific (audio/x-m4a, audio/opus), or transcoder-mangled types resolve to a MIME type the WhatsApp Cloud API accepts.
  • On success, it unmarshals the response into a Media type and returns the media ID.

func (*Client) Headers

func (c *Client) Headers(contentType string) []xhttp.HTTPData

Headers returns a slice of xhttp.HTTPData containing the standard headers needed for API requests, including the specified Content-Type and the Bearer Authorization token.

func (*Client) SendContact

func (c *Client) SendContact(
	receiverNumber,
	contactName,
	contactPhone string,
) (id string, err error)

SendContact sends a contact card to a specific WhatsApp recipient.

  • The receiverNumber may be a phone number or a BSUID; see SetRecipient for routing.
  • It uses xjson.JSON to construct the request body and interacts with the WhatsApp Messages API.
  • Returns the message ID or an error if the validation or the MessagesEndpointRequest fails.

func (*Client) SendInteractiveList

func (api *Client) SendInteractiveList(
	h Header,
	opts SendInteractiveListOpts,
) (id string, err error)

SendInteractiveList sends an interactive list message through the WhatsApp API.

func (*Client) SendLocation

func (api *Client) SendLocation(
	h Header,
	location Location,
) (id string, err error)

SendLocation sends a location message through the WhatsApp API.

  • It receives a Header and a Location as parameters.
  • Returns the ID of the sent message or an error if the request fails.

func (*Client) SendQuickReplyMessage

func (api *Client) SendQuickReplyMessage(
	h Header,
	enterpriseName, message string,
	buttons []QuickReplyButton,
) (id string, err error)

SendQuickReplyMessage sends an interactive message containing quick reply buttons.

func (*Client) SenderID

func (c *Client) SenderID() string

SenderID returns the current sender ID configured in the Client.

type Cost

type Cost struct {
	Type string `json:"type"`
}

Cost represents the cost metrics associated with the message.

type CreateTemplateResponse

type CreateTemplateResponse struct {
	Id string `json:"id"`
}

CreateTemplateResponse contains the identification data returned by the API after a successful template creation.

type Cursors

type Cursors struct {
	After  string `json:"after"`
	Before string `json:"before"`
}

Cursors holds the pointers for the next and previous pages.

type DataItem

type DataItem struct {
	DataPoints  []DataPoint `json:"data_points"`
	Granularity string      `json:"granularity"`
	ProductType string      `json:"product_type"`
}

DataItem contains metrics grouped by product type and granularity.

type DataPoint

type DataPoint struct {
	Clicked    []Clicked `json:"clicked"`
	Cost       []Cost    `json:"cost"`
	Delivered  int       `json:"delivered"`
	End        int64     `json:"end"`
	Read       int       `json:"read"`
	Sent       int       `json:"sent"`
	Start      int64     `json:"start"`
	TemplateID string    `json:"template_id"`
}

DataPoint holds the actual metrics for a specific template during a time window.

type EventEmitter

type EventEmitter interface {
	Emit(eventName string, data any)
}

EventEmitter defines the interface for emitting events.

type Gender

type Gender string

Gender represents the grammatical gender of a word.

const (
	Masculine Gender = "M"
	Feminine  Gender = "F"
	Neutral   Gender = "N"
)
type Header = xjson.JSON

Header is an alias for xjson.JSON used to define message headers.

func MessageHeader

func MessageHeader(
	receiverNumber string,
	msgType string,
	replyId ...string,
) Header

MessageHeader creates a basic Header for a WhatsApp message. It sets the recipient, message type, and optionally a reply context if replyId is provided.

The receiverNumber may be a phone number or a BSUID (for example "US.13491208655302741918"). A BSUID is routed to the "recipient" field while a phone number keeps using "to", so existing callers need no payload change. See SetRecipient for the routing rules.

type InfoData

type InfoData struct {
	About        string   `json:"about"`
	Address      string   `json:"address"`
	Email        string   `json:"email"`
	Websites     []string `json:"websites"`
	Description  string   `json:"description"`
	ProfilePhoto string   `json:"profile_picture_url"`
	Vertical     string   `json:"vertical"`
	Name         string   `json:"name,omitempty"`
}

InfoData contains the details of a WhatsApp business profile, such as email, address, and description.

type InfoResponse

type InfoResponse struct {
	Data []InfoData `json:"data"`
}

InfoResponse represents the API response containing a list of InfoData.

type InitCall

type InitCall struct {
	CallId string `json:"callId"`
	AppId  string `json:"appId"`
}

InitCall holds the initialization data for an outbound call, containing the CallId and AppId.

type InteractiveListRow

type InteractiveListRow struct {
	Id          string `json:"id"`
	Title       string `json:"title"`
	Description string `json:"description"`
}

InteractiveListRow represents an individual row item within an interactive list section.

type InviteCallResponse

type InviteCallResponse struct {
	Id     string `json:"id,omitempty"`
	CallId string `json:"call_id,omitempty"`
}

InviteCallResponse represents the API response payload when inviting a call.

type Lang

type Lang string

Lang represents the supported language codes for WhatsApp message templates.

const (
	English           Lang = "en_US"
	Spanish           Lang = "es_ES"
	EnglishUK         Lang = "en_GB"
	PortugueseBrazil  Lang = "pt_BR"
	French            Lang = "fr"
	German            Lang = "de"
	ChineseSimplified Lang = "zh_CN"
	Arabic            Lang = "ar"
	Hindi             Lang = "hi"
	Japanese          Lang = "ja"
)

type LangMsgRef

type LangMsgRef struct {
	Lang Lang
	Ref  MsgReference
}

LangMsgRef represents the composite key for the translations map.

type Location

type Location struct {
	// Latitude is the north-south coordinate of the location.
	Latitude float64 `json:"latitude"`
	// Longitude is the east-west coordinate of the location.
	Longitude float64 `json:"longitude"`
	// Name is the name of the location (e.g., "Googleplex").
	Name string `json:"name,omitempty"`
	// Address is the physical address of the location.
	Address string `json:"address,omitempty"`
}

Location represents a geographic location with its coordinates and optional descriptive metadata.

type MarketingMessage added in v1.0.0

type MarketingMessage struct {
	MessagingProduct string     `json:"messaging_product,omitempty"`
	RecipientType    string     `json:"recipient_type,omitempty"`
	To               string     `json:"to,omitempty"`
	Recipient        string     `json:"recipient,omitempty"`
	Type             string     `json:"type,omitempty"`
	Template         xjson.JSON `json:"template,omitempty"`
}

MarketingMessage models a WhatsApp Marketing Messages API payload. It mirrors the documented fields a marketing request may carry: a recipient addressed by phone number (MarketingMessage.To) or BSUID (MarketingMessage.Recipient), the message type, and the free-form template content.

func BuildMarketingMessage added in v1.0.0

func BuildMarketingMessage(body []byte) (*MarketingMessage, error)

BuildMarketingMessage decodes a raw marketing message payload into a MarketingMessage and normalizes its recipient. When the "to" field holds a BSUID (for example "US.13491208655302741918"), the value is moved to the "recipient" field as required by the Marketing Messages API, so existing callers may keep placing either a phone number or a BSUID in "to" without changing their payload. A value already supplied in "recipient" is preserved.

func (*MarketingMessage) Bytes added in v1.0.0

func (m *MarketingMessage) Bytes() []byte

Bytes marshals the MarketingMessage into the JSON payload expected by SendMarketingMessage.

type Media

type Media struct {
	Id       string `json:"id"`
	Filename string `json:"filename,omitempty"`
	Caption  string `json:"caption,omitempty"`
}

Media represents the media object structure for WhatsApp messages (Audio, Image, Video, etc).

type Message

type Message = xjson.JSON

Message is an alias for xjson.JSON representing the final message payload.

func AudioMessage

func AudioMessage(h Header, audio Media) Message

AudioMessage attaches an Media audio object to the Header.

func AuthTemplate

func AuthTemplate(
	name string,
	to string,
	token string,
	lang Lang,
) Message

AuthTemplate generates an authentication template Message to be sent via WhatsApp.

  • It constructs the payload using the provided template name, recipient number (to [string]), authentication token [string], and language Lang. The resulting message utilizes xjson.JSON to define the template components, including a text body and a URL button parameter that both contain the provided token.

func DocumentMessage

func DocumentMessage(h Header, document Media) Message

DocumentMessage attaches an Media document object to the Header.

func ImageMessage

func ImageMessage(h Header, image Media) Message

ImageMessage attaches an Media image object to the Header.

func MessageTemplate

func MessageTemplate(
	h Header,
	template xjson.JSON,
) Message

MessageTemplate creates a Message by configuring the Header with the provided xjson.JSON template. It sets the message type to "template" and assigns the template data to the header.

func Reaction

func Reaction(h Header, reaction ReactionBody) Message

Reaction attaches a ReactionBody to the Header.

func ScheduleConfirmationTemplate

func ScheduleConfirmationTemplate(
	h Header,
	opts ScheduleConfirmationTemplateOptions,
) Message

ScheduleConfirmationTemplate generates a localized confirmation Message based on the provided Header and ScheduleConfirmationTemplateOptions.

  • It calculates the event hour, determines the correct grammatical gender for the event title, and constructs a JSON payload with the appropriate translations.
  • It appends any provided [scheduleUrls] as text parameters within the template components.

func SchedulingTemplate

func SchedulingTemplate(
	h Header,
	opts SchedulingTemplateOptions,
) Message

func StickerMessage

func StickerMessage(h Header, sticker Media) Message

StickerMessage attaches an Media sticker object to the Header.

func TextMessage

func TextMessage(h Header, body string) Message

TextMessage appends a text body to the provided Header and returns it as a Message.

func VideoMessage

func VideoMessage(h Header, video Media) Message

VideoMessage attaches an Media video object to the Header.

type MessageSent

type MessageSent struct {
	Id string `json:"id"`
}

MessageSent represents the basic information of a message successfully sent by the API.

type MessageType

type MessageType string

MessageType represents the classification of a WhatsApp message.

const (
	Audio    MessageType = "AUDIO"
	Image    MessageType = "IMAGE"
	Video    MessageType = "VIDEO"
	Document MessageType = "DOCUMENT"
	Text     MessageType = "TEXT"
	Sticker  MessageType = "STICKER"
)

Standard MessageType constants representing the supported WhatsApp message classifications.

func NewMessageType

func NewMessageType(contentType string) MessageType

NewMessageType evaluates the given contentType string and returns the corresponding MessageType. If the content type indicates text, it returns Text. Otherwise, it maps the content type to Audio, Video, Image, or Sticker. It defaults to Document if no match is found.

func (MessageType) String

func (m MessageType) String() string

String returns the string representation of the MessageType.

type MessagesSent

type MessagesSent []MessageSent

MessagesSent is a slice of MessageSent.

func (MessagesSent) FirstId

func (m MessagesSent) FirstId() string

FirstId returns the ID of the first message in the slice, or an empty string if empty.

func (MessagesSent) Len

func (m MessagesSent) Len() int

Len returns the number of messages in the MessagesSent slice.

type MsgReference

type MsgReference string
const (
	RefEventMasc    MsgReference = "event_masc"
	RefEventFem     MsgReference = "event_fem"
	RefEventNeutral MsgReference = "event_neutral"
	RefGreeting     MsgReference = "greeting"
)

type MultipartWriter

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

MultipartWriter is a custom wrapper around the standard multipart.Writer to simplify the creation of multipart requests.

func NewMultipartWriter

func NewMultipartWriter(body io.Writer) *MultipartWriter

NewMultipartWriter initializes and returns a new MultipartWriter that writes its output to the provided io.Writer.

func (*MultipartWriter) Close

func (w *MultipartWriter) Close() error

Close finishes the multipart message by writing the trailing boundary end line.

func (*MultipartWriter) CreatePart

func (w *MultipartWriter) CreatePart(header textproto.MIMEHeader) (io.Writer, error)

CreatePart creates a new part in the multipart payload using the given textproto.MIMEHeader. It returns an io.Writer to which the contents of the part can be written.

func (*MultipartWriter) Value

func (w *MultipartWriter) Value() *multipart.Writer

Value returns the underlying multipart.Writer instance used by the wrapper.

func (*MultipartWriter) WriteField

func (w *MultipartWriter) WriteField(fieldname, value string) error

WriteField calls the underlying writer to append a standard form field with the specified field name and value.

type Paging

type Paging struct {
	Cursors Cursors `json:"cursors"`
	Next    string  `json:"next"`
}

Paging contains navigation metadata for paginated results.

type Profile

type Profile struct {
	PhoneNumberID string
	// contains filtered or unexported fields
}

Profile represents a WhatsApp business profile.

func NewProfile

func NewProfile(
	ctx context.Context,
	phoneNumberId,
	accessToken string,
) *Profile

NewProfile creates and returns a new Profile.

  • It initializes the profile using the provided phone number ID and access token, internally calling Default to set up the Client.

func (*Profile) ChangeAbout

func (p *Profile) ChangeAbout(about string) error

ChangeAbout updates the "about" text of the business profile.

func (*Profile) ChangeAddress

func (p *Profile) ChangeAddress(address string) error

ChangeAddress updates the physical address of the business profile.

func (*Profile) ChangeDescription

func (p *Profile) ChangeDescription(description string) error

ChangeDescription updates the description of the business profile.

func (*Profile) ChangeEmail

func (p *Profile) ChangeEmail(email string) error

ChangeEmail updates the contact email of the business profile.

func (*Profile) ChangeProfilePicture

func (p *Profile) ChangeProfilePicture(
	appId string,
	mediaFile *multipart.FileHeader,
) (ProfilePictureData, error)

ChangeProfilePicture updates the business profile picture.

  • It first uploads the media file using UploadTemplateFile, and then assigns it to the profile.

func (*Profile) ChangeVertical

func (p *Profile) ChangeVertical(vertical ProfileVertical) error

ChangeVertical updates the industry vertical category of the business profile using a ProfileVertical.

func (*Profile) ChangeWebsites

func (p *Profile) ChangeWebsites(websites []string) error

ChangeWebsites updates the list of websites associated with the business profile.

func (*Profile) Info

func (p *Profile) Info(accountName string) (InfoData, error)

Info retrieves the business profile information and returns an InfoData.

  • It fetches details including the about text, address, description, email, profile picture URL, websites, and vertical.

type ProfilePictureData

type ProfilePictureData struct {
	Name string `json:"name"`
	Size int64  `json:"size"`
	Type string `json:"type"`
}

ProfilePictureData represents the data returned after successfully updating a profile picture.

type ProfileVertical

type ProfileVertical string

ProfileVertical represents the industry vertical category for a business profile.

const (
	// ALCOHOL represents the alcohol industry [ProfileVertical].
	ALCOHOL ProfileVertical = "ALCOHOL"
	// APPAREL represents the apparel and clothing [ProfileVertical].
	APPAREL ProfileVertical = "APPAREL"
	// AUTO represents the automotive industry [ProfileVertical].
	AUTO ProfileVertical = "AUTO"
	// BEAUTY represents the beauty and personal care [ProfileVertical].
	BEAUTY ProfileVertical = "BEAUTY"
	// EDU represents the education sector [ProfileVertical].
	EDU ProfileVertical = "EDU"
	// ENTERTAIN represents the entertainment industry [ProfileVertical].
	ENTERTAIN ProfileVertical = "ENTERTAIN"
	// EVENT_PLAN represents the event planning [ProfileVertical].
	EVENT_PLAN ProfileVertical = "EVENT_PLAN"
	// FINANCE represents the financial services [ProfileVertical].
	FINANCE ProfileVertical = "FINANCE"
	// GOVT represents government and public administration [ProfileVertical].
	GOVT ProfileVertical = "GOVT"
	// GROCERY represents the grocery and food retail [ProfileVertical].
	GROCERY ProfileVertical = "GROCERY"
	// HEALTH represents the healthcare and medical [ProfileVertical].
	HEALTH ProfileVertical = "HEALTH"
	// HOTEL represents the hotel and lodging [ProfileVertical].
	HOTEL ProfileVertical = "HOTEL"
	// NONPROFIT represents non-profit organizations [ProfileVertical].
	NONPROFIT ProfileVertical = "NONPROFIT"
	// ONLINE_GAMBLING represents the online gambling [ProfileVertical].
	ONLINE_GAMBLING ProfileVertical = "ONLINE_GAMBLING"
	// OTC_DRUGS represents over-the-counter drugs and pharmacies [ProfileVertical].
	OTC_DRUGS ProfileVertical = "OTC_DRUGS"
	// OTHER represents any other unspecified [ProfileVertical].
	OTHER ProfileVertical = "OTHER"
	// PHYSICAL_GAMBLING represents physical gambling and casinos [ProfileVertical].
	PHYSICAL_GAMBLING ProfileVertical = "PHYSICAL_GAMBLING"
	// PROF_SERVICES represents professional services [ProfileVertical].
	PROF_SERVICES ProfileVertical = "PROF_SERVICES"
	// RESTAURANT represents the restaurant and food service [ProfileVertical].
	RESTAURANT ProfileVertical = "RESTAURANT"
	// RETAIL represents general retail [ProfileVertical].
	RETAIL ProfileVertical = "RETAIL"
	// TRAVEL represents the travel and tourism [ProfileVertical].
	TRAVEL ProfileVertical = "TRAVEL"
)

func NewProfileVertical

func NewProfileVertical(v string) ProfileVertical

NewProfileVertical creates and returns a new ProfileVertical from the provided string v.

type QuickReplyButton

type QuickReplyButton struct {
	Type  string      `json:"type"`
	Reply ReplyButton `json:"reply"`
}

QuickReplyButton represents a quick reply button used in an interactive message.

func GenerateQuickReplyButton

func GenerateQuickReplyButton(
	id, title string,
) QuickReplyButton

GenerateQuickReplyButton is a helper function that creates and returns a new QuickReplyButton.

type ReactionBody

type ReactionBody struct {
	MessageId string `json:"message_id"`
	Emoji     string `json:"emoji"`
}

ReactionBody defines the structure for sending an emoji reaction to a specific message.

type ReplyButton

type ReplyButton struct {
	Id    string `json:"id"`
	Title string `json:"title"`
}

ReplyButton contains the unique identifier and the title text for a quick reply button.

type ScheduleConfirmationTemplateOptions

type ScheduleConfirmationTemplateOptions struct {
	Name,
	EventTitle,
	CustomerName string
	StartTime, Now time.Time
	Urls           scheduleUrls
	Lang           Lang
}

ScheduleConfirmationTemplateOptions holds the configuration fields required to build a schedule confirmation template. It includes details such as the event's start time (time.Time), current time (time.Time), a list of related URLs ([scheduleUrls]), and the target language (Lang).

type SchedulingTemplateOptions

type SchedulingTemplateOptions struct {
	Lang           Lang
	TemplateName   string
	ScheduleLayout TimeLayout
	StartTime      time.Time
	Timezone       string
}

type SendInteractiveListOpts

type SendInteractiveListOpts struct {
	Header     string                          `json:"header"`
	Message    string                          `json:"message"`
	Footer     string                          `json:"footer"`
	ButtonText string                          `json:"btnTxt"`
	Rows       map[string][]InteractiveListRow `json:"rows"`
}

SendInteractiveListOpts contains the configuration and content for sending an interactive list message.

type SendMessageResponse

type SendMessageResponse struct {
	MessagesSent `json:"messages"`
	Success      bool `json:"success"`
}

SendMessageResponse represents the API response containing the list of sent messages.

func MessagesEndpointRequest

func MessagesEndpointRequest(
	whats *Client,
	b []byte,
) (SendMessageResponse, error)

MessagesEndpointRequest performs a request to the messages endpoint.

func SendMarketingMessage

func SendMarketingMessage(
	api *Client,
	body []byte,
) (*SendMessageResponse, error)

SendMarketingMessage sends a marketing message using the WhatsApp API.

  • It requires a Client and a byte slice representing the JSON payload.
  • It returns a SendMessageResponse and an error if the HTTP request fails,
  • if the response cannot be decoded, or if the message could not be sent.

func SendMessage

func SendMessage(
	whats *Client,
	body Message,
) (*SendMessageResponse, error)

SendMessage sends a Message using the provided Client.

func (SendMessageResponse) Ok

func (r SendMessageResponse) Ok() bool

Ok reports whether the /messages request was accepted by the Meta API.

The endpoint serves two operations: sending a message confirms success by returning at least one message id, while marking a message as read returns {"success": true} with no message id. Either signal counts as success; an error envelope decodes into a zero-valued struct and is therefore rejected.

type TemplateFields

type TemplateFields struct {
	Name       string
	Category   Category
	Lang       Lang
	Components []xjson.JSON
}

TemplateFields holds the necessary input data to define a new message template.

type TemplateStatus

type TemplateStatus struct {
	Id     string `json:"id"`
	Name   string `json:"name"`
	Status status `json:"status"`
}

TemplateStatus represents the status information of a WhatsApp template.

type Templates

type Templates[T any] struct {
	Data []T `json:"data"`
}

Templates represents a generic structure for holding WhatsApp templates data.

func GetJSONTemplates

func GetJSONTemplates(client *Client) (Templates[xjson.JSON], error)

GetJSONTemplates retrieves all message templates as raw xjson.JSON data using the provided Client.

func GetTemplateStatus

func GetTemplateStatus(client *Client, name string) (Templates[TemplateStatus], error)

GetTemplateStatus retrieves the TemplateStatus for a specific template by its name using the provided Client.

func GetTemplates

func GetTemplates[T any](client *Client, options *xhttp.Options) (Templates[T], error)

GetTemplates retrieves a list of message templates using the provided Client and xhttp.Options.

type TimeLayout

type TimeLayout string

TimeLayout represents a date and time format string based on the Go reference time.

const (
	// TimeLayoutEN is the layout for [English].
	TimeLayoutEN TimeLayout = "01/02/2006 at 03:04 PM"

	// TimeLayoutES is the layout for [Spanish].
	TimeLayoutES TimeLayout = "02/01/2006 a las 15:04"

	// TimeLayoutENGB is the layout for [EnglishUK].
	TimeLayoutENGB TimeLayout = "02/01/2006 at 15:04"

	// TimeLayoutPT is the layout for [PortugueseBrazil].
	TimeLayoutPT TimeLayout = "02/01/2006 às 15:04"

	// TimeLayoutFR is the layout for [French].
	TimeLayoutFR TimeLayout = "02/01/2006 à 15:04"

	// TimeLayoutDE is the layout for [German].
	TimeLayoutDE TimeLayout = "02.01.2006 um 15:04"

	// TimeLayoutZH is the layout for [ChineseSimplified].
	TimeLayoutZH TimeLayout = "2006年01月02日 15:04"

	// TimeLayoutAR is the layout for [Arabic].
	TimeLayoutAR TimeLayout = "02/01/2006 في 15:04"

	// TimeLayoutHI is the layout for [Hindi].
	TimeLayoutHI TimeLayout = "02/01/2006 15:04"

	// TimeLayoutJA is the layout for [Japanese].
	TimeLayoutJA TimeLayout = "2006年01月02日 15:04"
)

func NewTimeLayout

func NewTimeLayout(lang Lang) (TimeLayout, error)

NewTimeLayout returns the corresponding TimeLayout for the provided Lang.

func (TimeLayout) String

func (s TimeLayout) String() string

String returns the string representation of the TimeLayout.

type TmplAnalytics

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

TmplAnalytics handles template-related analytical operations.

func TemplateAnalytics

func TemplateAnalytics(
	whats *Client,
) *TmplAnalytics

TemplateAnalytics creates a new instance of TmplAnalytics.

func (*TmplAnalytics) Enable

func (api *TmplAnalytics) Enable() bool

Enable activates insights for the configured sender ID. Returns true if the operation was successful.

func (*TmplAnalytics) WithInterval

func (api *TmplAnalytics) WithInterval(
	templateIDs []string,
	interval TmplAnalyticsInterval,
	paging ...Paging,
) (*TmplAnalyticsResponse, error)

WithInterval retrieves template analytics metrics within a specific time interval. It supports filtering by template IDs and handles pagination via Paging.

type TmplAnalyticsInterval

type TmplAnalyticsInterval struct {
	Start, End time.Time
}

TmplAnalyticsInterval defines a time range for analytical queries.

type TmplAnalyticsResponse

type TmplAnalyticsResponse struct {
	Data   []DataItem `json:"data"`
	Paging Paging     `json:"paging"`
}

TmplAnalyticsResponse represents the structure of the API response for analytics.

func (*TmplAnalyticsResponse) Bytes

func (data *TmplAnalyticsResponse) Bytes() []byte

Bytes serializes TmplAnalyticsResponse into a JSON byte slice using xjson.Bytes.

type UploadSession

type UploadSession struct {
	Id string `json:"id"`
}

UploadSession holds the data returned when a session is initialized, primarily the session ID used for further upload steps.

type UploadedFileHandle

type UploadedFileHandle struct {
	H string `json:"h"`
}

UploadedFileHandle contains the handle hash returned by the API once the file payload has been completely uploaded.

type UploadedTemplateFile

type UploadedTemplateFile struct {
	Id      string `json:"id"`
	Session string `json:"session"`
	// contains filtered or unexported fields
}

UploadedTemplateFile represents a file that has been successfully uploaded and is ready to be used as a template media.

func UploadTemplateFile

func UploadTemplateFile(
	client *Client,
	appId string,
	mediaFile *multipart.FileHeader,
) (UploadedTemplateFile, error)

UploadTemplateFile handles the entire upload workflow for a media template file. It opens the provided multipart.FileHeader, creates an UploadSession using the Client, and then uploads the bytes to generate a file handle. It returns an UploadedTemplateFile containing the ID and Session.

type WebhookPin

type WebhookPin struct {
	Register  string
	Subscribe string
}

WebhookPin defines the necessary credentials for the registration and subscription steps of the WhatsApp Webhook.

Directories

Path Synopsis
Package group provides abstractions and functions to manage WhatsApp groups through the Meta API.
Package group provides abstractions and functions to manage WhatsApp groups through the Meta API.

Jump to

Keyboard shortcuts

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