whatsapp

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2023 License: MIT Imports: 17 Imported by: 0

README

whatsapp

SETUP

pre requisites

To be able to test/use this api you need Access Token, Phone number ID and Business ID. For that tou need to register as a Meta Developer. You can register here https://developers.facebook.com/docs/development/register

Then create an application here https://developers.facebook.com/docs/development/create-an-app and configre it to enable access to WhatsApp Business Cloud API.

You can manage your apps here https://developers.facebook.com/apps/

From Whatsapp Developer Dashboard you can try and send a test message to your phone number. to be sure that everything is working fine before you start using this api.

When all the above is done you can start using this api.

Head over to HOWTO file

Documentation

Index

Examples

Constants

View Source
const (
	BaseURL                   = "https://graph.facebook.com/"
	LowestSupportedVersion    = "v16.0"
	ContactBirthDayDateFormat = "2006-01-02" // YYYY-MM-DD
)
View Source
const (
	MaxAudioSize         = 16 * 1024 * 1024  // 16 MB
	MaxDocSize           = 100 * 1024 * 1024 // 100 MB
	MaxImageSize         = 5 * 1024 * 1024   // 5 MB
	MaxVideoSize         = 16 * 1024 * 1024  // 16 MB
	MaxStickerSize       = 100 * 1024        // 100 KB
	UploadedMediaTTL     = 30 * 24 * time.Hour
	MediaDownloadLinkTTL = 5 * time.Minute
)
View Source
const (
	// MessageStatusRead is the status for a read message.
	MessageStatusRead = "read"
)

Variables

View Source
var ErrBadRequestFormat = errors.New("bad request")
View Source
var ErrMediaDownload = fmt.Errorf("failed to download media")

Functions

func MediaMaxAllowedSize

func MediaMaxAllowedSize(mediaType MediaType) int

MediaMaxAllowedSize returns the allowed maximum size for media. It returns -1 for unknown media type. Currently, it checks for MediaTypeAudio,MediaTypeVideo, MediaTypeImage, MediaTypeSticker,MediaTypeDocument.

Types

type CacheOptions

type CacheOptions struct {
	CacheControl string `json:"cache_control,omitempty"`
	LastModified string `json:"last_modified,omitempty"`
	ETag         string `json:"etag,omitempty"`
	Expires      int64  `json:"expires,omitempty"`
}

CacheOptions contains the options on how to send a media message. You can specify either the ID or the link of the media. Also, it allows you to specify caching options.

The Cloud API supports media http caching. If you are using a link (link) to a media asset on your server (as opposed to the ID (id) of an asset you have uploaded to our servers),you can instruct us to cache your asset for reuse with future messages by including the headers below in your server response when we request the asset. If none of these headers are included, we will not cache your asset.

Cache-Control: <CACHE_CONTROL>
Last-Modified: <LAST_MODIFIED>
ETag: <ETAG>

CacheControl

The Cache-Control header tells us how to handle asset caching. We support the following directives:

max-age=n: Indicates how many seconds (n) to cache the asset. We will reuse the cached asset in subsequent
messages until this time is exceeded, after which we will request the asset again, if needed.
Example: Cache-Control: max-age=604800.

no-cache: Indicates the asset can be cached but should be updated if the Last-Modified header value
is different from a previous response.Requires the Last-Modified header.
Example: Cache-Control: no-cache.

no-store: Indicates that the asset should not be cached. Example: Cache-Control: no-store.

private: Indicates that the asset is personalized for the recipient and should not be cached.

LastModified

Last-Modified Indicates when the asset was last modified. Used with Cache-Control: no-cache. If the Last-Modified value is different from a previous response and Cache-Control: no-cache is included in the response, we will update our cached apiVersion of the asset with the asset in the response. Example: Date: Tue, 22 Feb 2022 22:22:22 GMT.

ETag

The ETag header is a unique string that identifies a specific apiVersion of an asset. Example: ETag: "33a64df5". This header is ignored unless both Cache-Control and Last-Modified headers are not included in the response. In this case, we will cache the asset according to our own, internal logic (which we do not disclose).

type Client

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

Client includes the http client, base url, apiVersion, access token, phone number id, and whatsapp business account id. which are used to make requests to the whatsapp api. Example:

	client := whatsapp.NewClient(
		whatsapp.WithHTTPClient(http.DefaultClient),
		whatsapp.WithBaseURL(whatsapp.BaseURL),
		whatsapp.WithVersion(whatsapp.LowestSupportedVersion),
		whatsapp.WithAccessToken("access_token"),
		whatsapp.WithPhoneNumberID("phone_number_id"),
		whatsapp.WithBusinessAccountID("whatsapp_business_account_id"),
	)
 // create a text message
 message := whatsapp.TextMessage{
 	Recipient: "<phone_number>",
 	Message:   "Hello World",
     PreviewURL: false,
 }

// send the text message

_, err := client.SendTextMessage(context.Background(), message)
if err != nil {
	log.Fatal(err)
}

func NewClient

func NewClient(opts ...ClientOption) *Client
Example
client := NewClient(
	WithHTTPClient(http.DefaultClient),
	WithBaseURL(BaseURL),
	WithVersion(LowestSupportedVersion),
	WithAccessToken("access_token"),
	WithPhoneNumberID("phone_number_id"),
	WithBusinessAccountID("whatsapp_business_account_id"),
	WithHooks(nil),
)

client.SetAccessToken("myexampletoken")
client.SetPhoneNumberID("myexamplephoneid")
client.SetBusinessAccountID("businessaccountID")

cctx := client.context()

fmt.Printf("base url: %s\napi version: %s\ntoken: %s\nphone id: %s\nbusiness id: %s\n",
	cctx.baseURL, cctx.apiVersion, cctx.accessToken, cctx.phoneNumberID, cctx.businessAccountID)
Output:

base url: https://graph.facebook.com/
api version: v16.0
token: myexampletoken
phone id: myexamplephoneid
business id: businessaccountID

func (*Client) CreateQrCode

func (client *Client) CreateQrCode(ctx context.Context, message *qrcodes.CreateRequest) (
	*qrcodes.CreateResponse, error,
)

func (*Client) DeleteMedia

func (client *Client) DeleteMedia(ctx context.Context, mediaID string) (*DeleteMediaResponse, error)

DeleteMedia delete the media by using its corresponding media ID.

func (*Client) DeleteQrCode

func (client *Client) DeleteQrCode(ctx context.Context, qrCodeID string) (*qrcodes.SuccessResponse, error)

func (*Client) DownloadMedia

func (client *Client) DownloadMedia(ctx context.Context, mediaID string, retries int) (*DownloadMediaResponse, error)

DownloadMedia download the media by using its corresponding media ID. It uses the media ID to retrieve the media URL. All media URLs expire after 5 minutes —you need to retrieve the media URL again if it expires. If successful, *DownloadMediaResponse will be returned. It contains headers and io.Reader. From the headers you can check a content-type header to indicate the mime type of returned data.

If media fails to download, Facebook returns a 404 http status code. It is recommended to try to retrieve a new media URL and download it again. This will go on for an n retries. If doing so doesn't resolve the issue, please try to renew the access token, then retry downloading the media.

func (*Client) GetMediaInformation

func (client *Client) GetMediaInformation(ctx context.Context, mediaID string) (*MediaInformation, error)

GetMediaInformation retrieve the media object by using its corresponding media ID.

func (*Client) GetQrCode

func (client *Client) GetQrCode(ctx context.Context, qrCodeID string) (*qrcodes.Information, error)

func (*Client) ListPhoneNumbers

func (client *Client) ListPhoneNumbers(ctx context.Context, filters []*FilterParams) (*PhoneNumbersList, error)

ListPhoneNumbers returns a list of phone numbers that are associated with the business account. using the WhatsApp Business Management API.

You will need to have

  • The WhatsApp Business Account ID for the business' phone numbers you want to retrieve
  • A System User access token linked to your WhatsApp Business Account
  • The whatsapp_business_management permission

Limitations This API can only retrieve phone numbers that have been registered. Adding, updating, or deleting phone numbers is not permitted using the API.

The equivalent curl command to retrieve phone numbers is (formatted for readability):

	curl -X GET "https://graph.facebook.com/v16.0/{whatsapp-business-account-id}/phone_numbers
      	?access_token={system-user-access-token}"

On success, a JSON object is returned with a list of all the business names, phone numbers, phone number IDs, and quality ratings associated with a business.

{
  "data": [
    {
      "verified_name": "Jasper's Market",
      "display_phone_number": "+1 631-555-5555",
      "id": "1906385232743451",
      "quality_rating": "GREEN"

	    },
	    {
	      "verified_name": "Jasper's Ice Cream",
	      "display_phone_number": "+1 631-555-5556",
	      "id": "1913623884432103",
	      "quality_rating": "NA"
	    }
	  ],
	}

Filter Phone Numbers You can query phone numbers and filter them based on their account_mode. This filtering option is currently being tested in beta mode. Not all developers have access to it.

Sample Request

curl -i -X GET "https://graph.facebook.com/v16.0/{whatsapp-business-account-ID}/phone_numbers?\
	filtering=[{"field":"account_mode","operator":"EQUAL","value":"SANDBOX"}]&access_token=access-token"

Sample Response

{
  "data": [
    {
      "id": "1972385232742141",
      "display_phone_number": "+1 631-555-1111",
      "verified_name": "John’s Cake Shop",
      "quality_rating": "UNKNOWN",
    }
  ],
  "paging": {
	"cursors": {
		"before": "abcdefghij",
		"after": "klmnopqr"
	}
   }
}

func (*Client) ListQrCodes

func (client *Client) ListQrCodes(ctx context.Context) (*qrcodes.ListResponse, error)

func (*Client) MarkMessageRead

func (client *Client) MarkMessageRead(ctx context.Context, messageID string) (*StatusResponse, error)

MarkMessageRead sends a read receipt for a message.

func (*Client) PhoneNumberByID

func (client *Client) PhoneNumberByID(ctx context.Context) (*PhoneNumber, error)

PhoneNumberByID returns the phone number associated with the given ID.

func (*Client) React

func (client *Client) React(ctx context.Context, recipient string, req *ReactMessage) (*ResponseMessage, error)

func (*Client) Reply

func (client *Client) Reply(ctx context.Context, recipient string, req *ReplyMessage) (*ResponseMessage, error)

func (*Client) RequestVerificationCode

func (client *Client) RequestVerificationCode(ctx context.Context,
	codeMethod VerificationMethod, language string,
) error

RequestVerificationCode requests a verification code to be sent via SMS or VOICE. doc link: https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers

You need to verify the phone number you want to use to send messages to your customers. After the API call, you will receive your verification code via the method you selected. To finish the verification process, include your code in the VerifyCode method.

Example
client := NewClient(
	WithHTTPClient(http.DefaultClient),
	WithBaseURL(BaseURL),
	WithVersion(LowestSupportedVersion),
	WithAccessToken("access_token"),
	WithPhoneNumberID("phone_number_id"),
	WithBusinessAccountID("whatsapp_business_account_id"),
)

err := client.RequestVerificationCode(context.TODO(), SMSVerificationMethod, "en_US")
if err != nil {
	fmt.Println(err)
}
err = client.RequestVerificationCode(context.TODO(), VoiceVerificationMethod, "en_US")
if err != nil {
	fmt.Println(err)
}
Output:

func (*Client) SendContacts

func (client *Client) SendContacts(ctx context.Context, recipient string, contacts []*models.Contact) (
	*ResponseMessage, error,
)

func (*Client) SendInteractiveMessage added in v0.0.2

func (client *Client) SendInteractiveMessage(ctx context.Context, recipient string, req *models.Interactive) (
	*ResponseMessage, error,
)

SendInteractiveMessage sends an interactive message to the recipient.

func (*Client) SendInteractiveTemplate added in v0.0.2

func (client *Client) SendInteractiveTemplate(ctx context.Context, recipient string, req *InteractiveTemplateRequest) (
	*ResponseMessage, error,
)

SendInteractiveTemplate send an interactive template message which contains some buttons for user intraction. Interactive message templates expand the content you can send recipients beyond the standard message template and media messages template types to include interactive buttons using the components object. There are two types of predefined buttons:

  • Call-to-Action — Allows your customer to call a phone number and visit a website.
  • Quick Reply — Allows your customer to return a simple text message.

These buttons can be attached to text messages or media messages. Once your interactive message templates have been created and approved, you can use them in notification messages as well as customer service/care messages.

func (*Client) SendLocationMessage

func (client *Client) SendLocationMessage(ctx context.Context, recipient string,
	message *models.Location,
) (*ResponseMessage, error)

SendLocationMessage sends a location message to a WhatsApp Business Account.

func (*Client) SendMedia

func (client *Client) SendMedia(ctx context.Context, recipient string, req *MediaMessage,
	cacheOptions *CacheOptions,
) (*ResponseMessage, error)

SendMedia sends a media message to the recipient. Media can be sent using ID or Link. If using id, you must first upload your media asset to our servers and capture the returned media ID. If using link, your asset must be on a publicly accessible server or the message will fail to send.

func (*Client) SendMediaTemplate added in v0.0.2

func (client *Client) SendMediaTemplate(ctx context.Context, recipient string, req *MediaTemplateRequest) (
	*ResponseMessage, error,
)

SendMediaTemplate sends a media template message to the recipient. This kind of template message has a media message as a header. This is its main distinguishing feature from the text based template message.

func (*Client) SendTemplate

func (client *Client) SendTemplate(ctx context.Context, recipient string, req *Template) (*ResponseMessage, error)

SendTemplate sends a template message to the recipient. There are at the moment three types of templates messages you can send to the user, Text Based Templates, Media Based Templates and Interactive Templates. Text Based templates have a text message for a Header and Media Based templates have a Media message for a Header. Interactive Templates can have any of the above as a Header and also have a list of buttons that the user can interact with. You can use models.NewTextTemplate, models.NewMediaTemplate and models.NewInteractiveTemplate to create a Template. These are helper functions that will make your life easier.

func (*Client) SendTextMessage

func (client *Client) SendTextMessage(ctx context.Context, recipient string,
	message *TextMessage,
) (*ResponseMessage, error)

SendTextMessage sends a text message to a WhatsApp Business Account.

func (*Client) SendTextTemplate added in v0.0.2

func (client *Client) SendTextTemplate(ctx context.Context, recipient string, req *TextTemplateRequest) (
	*ResponseMessage, error,
)

SendTextTemplate sends a text template message to the recipient. This kind of template message has a text message as a header. This is its main distinguishing feature from the media based template message.

func (*Client) SetAccessToken

func (client *Client) SetAccessToken(accessToken string)

func (*Client) SetBusinessAccountID

func (client *Client) SetBusinessAccountID(businessAccountID string)

func (*Client) SetPhoneNumberID

func (client *Client) SetPhoneNumberID(phoneNumberID string)

func (*Client) UpdateQrCode

func (client *Client) UpdateQrCode(ctx context.Context, qrCodeID string, request *qrcodes.CreateRequest,
) (*qrcodes.SuccessResponse, error)

func (*Client) UploadMedia

func (client *Client) UploadMedia(ctx context.Context, mediaType MediaType, filename string,
	fr io.Reader,
) (*UploadMediaResponse, error)

func (*Client) VerifyCode

func (client *Client) VerifyCode(ctx context.Context, code string) (*StatusResponse, error)

VerifyCode should be run to verify the code retrieved by RequestVerificationCode.

type ClientOption

type ClientOption func(*Client)

func WithAccessToken

func WithAccessToken(accessToken string) ClientOption

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

func WithBusinessAccountID

func WithBusinessAccountID(whatsappBusinessAccountID string) ClientOption

func WithHTTPClient

func WithHTTPClient(http *http.Client) ClientOption

func WithHooks

func WithHooks(hooks ...whttp.Hook) ClientOption

func WithPhoneNumberID

func WithPhoneNumberID(phoneNumberID string) ClientOption

func WithVersion

func WithVersion(version string) ClientOption

type Cursors

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

type DeleteMediaResponse

type DeleteMediaResponse struct {
	Success bool `json:"success"`
}

type DownloadMediaResponse

type DownloadMediaResponse struct {
	Headers http.Header
	Body    io.Reader
}

type FilterParams

type FilterParams struct {
	Field    string `json:"field,omitempty"`
	Operator string `json:"operator,omitempty"`
	Value    string `json:"value,omitempty"`
}

type InteractiveTemplateRequest added in v0.0.2

type InteractiveTemplateRequest struct {
	Name           string
	LanguageCode   string
	LanguagePolicy string
	Headers        []*models.TemplateParameter
	Body           []*models.TemplateParameter
	Buttons        []*models.InteractiveButtonTemplate
}

type MediaInformation

type MediaInformation struct {
	MessagingProduct string `json:"messaging_product"`
	URL              string `json:"url"`
	MimeType         string `json:"mime_type"`
	Sha256           string `json:"sha256"`
	FileSize         int64  `json:"file_size"`
	ID               string `json:"id"`
}

type MediaMessage

type MediaMessage struct {
	Type      MediaType
	MediaID   string
	MediaLink string
	Caption   string
	Filename  string
	Provider  string
}

type MediaRequestParams

type MediaRequestParams struct {
	Token   string
	MediaID string
}

type MediaTemplateRequest added in v0.0.2

type MediaTemplateRequest struct {
	Name           string
	LanguageCode   string
	LanguagePolicy string
	Header         *models.TemplateParameter
	Body           []*models.TemplateParameter
}

type MediaType

type MediaType string
const (
	MediaTypeAudio    MediaType = "audio"
	MediaTypeDocument MediaType = "document"
	MediaTypeImage    MediaType = "image"
	MediaTypeSticker  MediaType = "sticker"
	MediaTypeVideo    MediaType = "video"
)

type MessageID

type MessageID struct {
	ID string `json:"id,omitempty"`
}

type MessageStatusUpdateRequest

type MessageStatusUpdateRequest struct {
	MessagingProduct string `json:"messaging_product,omitempty"` // always whatsapp
	Status           string `json:"status,omitempty"`            // always read
	MessageID        string `json:"message_id,omitempty"`
}

type MessageType

type MessageType string

MessageType represents the type of message currently supported. Which are Text messages,Reaction messages,MediaInformation messages,Location messages,Contact messages, and Interactive messages. You may also send any of these message types as a reply, except reaction messages. For more go to https://developers.facebook.com/docs/whatsapp/cloud-api/guides/send-messages

type Paging

type Paging struct {
	Cursors *Cursors `json:"cursors,omitempty"`
}

type PhoneNumber

type PhoneNumber struct {
	VerifiedName       string `json:"verified_name"`
	DisplayPhoneNumber string `json:"display_phone_number"`
	ID                 string `json:"id"`
	QualityRating      string `json:"quality_rating"`
}

type PhoneNumberNameStatus

type PhoneNumberNameStatus string

PhoneNumberNameStatus value can be one of the following: APPROVED: The name has been approved. You can download your certificate now. AVAILABLE_WITHOUT_REVIEW: The certificate for the phone is available and display name is ready to use without review. DECLINED: The name has not been approved. You cannot download your certificate. EXPIRED: Your certificate has expired and can no longer be downloaded. PENDING_REVIEW: Your name request is under review. You cannot download your certificate. NONE: No certificate is available.

type PhoneNumbersList

type PhoneNumbersList struct {
	Data    []*PhoneNumber `json:"data,omitempty"`
	Paging  *Paging        `json:"paging,omitempty"`
	Summary *Summary       `json:"summary,omitempty"`
}

type ReactMessage

type ReactMessage struct {
	MessageID string
	Emoji     string
}

type ReactRequest

type ReactRequest struct {
	BaseURL       string
	AccessToken   string
	PhoneNumberID string
	ApiVersion    string //nolint: revive,stylecheck
	Recipient     string
	MessageID     string
	Emoji         string
}

type ReplyMessage

type ReplyMessage struct {
	Context string
	Type    MessageType
	Content any
}

ReplyMessage is a message that is sent as a reply to a previous message. The previous message's ID is needed and is set as Context in ReplyRequest. Content is the message content. It can be a Text, Location, MediaInformation, Template, or Contact.

type ReplyRequest

type ReplyRequest struct {
	BaseURL       string
	AccessToken   string
	PhoneNumberID string
	ApiVersion    string //nolint: revive,stylecheck
	Recipient     string
	Context       string // this is ID of the message to reply to
	MessageType   MessageType
	Content       any // this is a Text if MessageType is Text
}

ReplyRequest contains options for replying to a message.

type ResponseContact

type ResponseContact struct {
	Input      string `json:"input"`
	WhatsappID string `json:"wa_id"`
}

type ResponseMessage

type ResponseMessage struct {
	Product  string             `json:"messaging_product,omitempty"`
	Contacts []*ResponseContact `json:"contacts,omitempty"`
	Messages []*MessageID       `json:"messages,omitempty"`
}

func React

func React(ctx context.Context, client *http.Client, req *ReactRequest, hooks ...whttp.Hook) (*ResponseMessage, error)

React sends a reaction to a message. To send reaction messages, make a POST call to /PHONE_NUMBER_ID/messages and attach a message object with type=reaction. Then, add a reaction object.

Sample request:

curl -X  POST \
 'https://graph.facebook.com/v15.0/FROM_PHONE_NUMBER_ID/messages' \
 -H 'Authorization: Bearer ACCESS_TOKEN' \
 -H 'Content-Type: application/json' \
 -d '{
  "messaging_product": "whatsapp",
  "recipient_type": "individual",
  "to": "PHONE_NUMBER",
  "type": "reaction",
  "reaction": {
    "message_id": "wamid.HBgLM...",
    "emoji": "\uD83D\uDE00"
  }
}'

If the message you are reacting to is more than 30 days old, doesn't correspond to any message in the conversation, has been deleted, or is itself a reaction message, the reaction message will not be delivered, and you will receive a webhooks with the code 131009.

A successful response includes an object with an identifier prefixed with wamid. Use the ID listed after wamid to track your message status.

Example response:

{
  "messaging_product": "whatsapp",
  "contacts": [{
      "input": "PHONE_NUMBER",
      "wa_id": "WHATSAPP_ID",
    }]
  "messages": [{
      "id": "wamid.ID",
    }]
}

func Reply

func Reply(ctx context.Context, client *http.Client, request *ReplyRequest,
	hooks ...whttp.Hook,
) (*ResponseMessage, error)

Reply is used to reply to a message. It accepts a ReplyRequest and returns a Response and an error. You can send any message as a reply to a previous message in a conversation by including the previous message's ID set as Context in ReplyRequest. The recipient will receive the new message along with a contextual bubble that displays the previous message's content.

Recipients will not see a contextual bubble if:

replying with a template message ("type":"template") replying with an image, video, PTT, or audio, and the recipient is on KaiOS These are known bugs which are being addressed. Example of Text reply: "messaging_product": "whatsapp",

  "context": {
    "message_id": "MESSAGE_ID"
  },
  "to": "<phone number> or <wa_id>",
  "type": "text",
  "text": {
    "preview_url": False,
    "body": "your-text-message-content"
  }
}'

func SendContact

func SendContact(ctx context.Context, client *http.Client, req *SendContactRequest,
	hooks ...whttp.Hook,
) (*ResponseMessage, error)

func SendLocation

func SendLocation(ctx context.Context, client *http.Client, req *SendLocationRequest,
	hooks ...whttp.Hook,
) (*ResponseMessage, error)

func SendMedia

func SendMedia(ctx context.Context, client *http.Client, req *SendMediaRequest,
	hooks ...whttp.Hook,
) (*ResponseMessage, error)

SendMedia sends a media message to the recipient. To send a media message, make a POST call to the /PHONE_NUMBER_ID/messages endpoint with type parameter set to audio, document, image, sticker, or video, and the corresponding information for the media type such as its ID or link (see MediaInformation http Caching).

Be sure to keep the following in mind:

  • Uploaded media only lasts thirty days
  • Generated download URLs only last five minutes
  • Always save the media ID when you upload a file

Here’s a list of the currently supported media types. Check out Supported MediaInformation Types for more information.

  • Audio (<16 MB) – ACC, MP4, MPEG, AMR, and OGG formats
  • Documents (<100 MB) – text, PDF, Office, and OpenOffice formats
  • Images (<5 MB) – JPEG and PNG formats
  • Video (<16 MB) – MP4 and 3GP formats
  • Stickers (<100 KB) – WebP format

Sample request using image with link:

curl -X  POST \
 'https://graph.facebook.com/v15.0/FROM-PHONE-NUMBER-ID/messages' \
 -H 'Authorization: Bearer ACCESS_TOKEN' \
 -H 'Content-Type: application/json' \
 -d '{
  "messaging_product": "whatsapp",
  "recipient_type": "individual",
  "to": "PHONE-NUMBER",
  "type": "image",
  "image": {
    "link" : "https://IMAGE_URL"
  }
}'

Sample request using media ID:

curl -X  POST \
 'https://graph.facebook.com/v15.0/FROM-PHONE-NUMBER-ID/messages' \
 -H 'Authorization: Bearer ACCESS_TOKEN' \
 -H 'Content-Type: application/json' \
 -d '{
  "messaging_product": "whatsapp",
  "recipient_type": "individual",
  "to": "PHONE-NUMBER",
  "type": "image",
  "image": {
    "id" : "MEDIA-OBJECT-ID"
  }
}'

A successful response includes an object with an identifier prefixed with wamid. If you are using a link to send the media, please check the callback events delivered to your Webhook server whether the media has been downloaded successfully.

{
  "messaging_product": "whatsapp",
  "contacts": [{
      "input": "PHONE_NUMBER",
      "wa_id": "WHATSAPP_ID",
    }]
  "messages": [{
      "id": "wamid.ID",
    }]
}

func SendTemplate

func SendTemplate(ctx context.Context, client *http.Client, req *SendTemplateRequest,
	hooks ...whttp.Hook,
) (*ResponseMessage, error)

func SendText

func SendText(ctx context.Context, client *http.Client, req *SendTextRequest,
	hooks ...whttp.Hook,
) (*ResponseMessage, error)

SendText sends a text message to the recipient.

type SendContactRequest

type SendContactRequest struct {
	BaseURL       string
	AccessToken   string
	PhoneNumberID string
	ApiVersion    string //nolint: revive,stylecheck
	Recipient     string
	Contacts      []*models.Contact
}

type SendLocationRequest

type SendLocationRequest struct {
	BaseURL       string
	AccessToken   string
	PhoneNumberID string
	ApiVersion    string //nolint: revive,stylecheck
	Recipient     string
	Name          string
	Address       string
	Latitude      float64
	Longitude     float64
}

type SendMediaRequest

type SendMediaRequest struct {
	BaseURL       string
	AccessToken   string
	PhoneNumberID string
	ApiVersion    string //nolint: revive,stylecheck
	Recipient     string
	Type          MediaType
	MediaID       string
	MediaLink     string
	Caption       string
	Filename      string
	Provider      string
	CacheOptions  *CacheOptions
}

type SendTemplateRequest

type SendTemplateRequest struct {
	BaseURL                string
	AccessToken            string
	PhoneNumberID          string
	ApiVersion             string //nolint: revive,stylecheck
	Recipient              string
	TemplateLanguageCode   string
	TemplateLanguagePolicy string
	TemplateName           string
	TemplateComponents     []*models.TemplateComponent
}

type SendTextRequest

type SendTextRequest struct {
	BaseURL       string
	AccessToken   string
	PhoneNumberID string
	ApiVersion    string //nolint: revive,stylecheck
	Recipient     string
	Message       string
	PreviewURL    bool
}

type StatusResponse

type StatusResponse struct {
	Success bool `json:"success,omitempty"`
}

type Summary

type Summary struct {
	TotalCount int `json:"total_count,omitempty"`
}

type Template

type Template struct {
	LanguageCode   string
	LanguagePolicy string
	Name           string
	Components     []*models.TemplateComponent
}

type TextMessage

type TextMessage struct {
	Message    string
	PreviewURL bool
}

type TextTemplateRequest added in v0.0.2

type TextTemplateRequest struct {
	Name           string
	LanguageCode   string
	LanguagePolicy string
	Body           []*models.TemplateParameter
}

type UploadMediaRequest

type UploadMediaRequest struct {
	MediaID  string
	FilePath string
	Type     MediaType
	Product  string
}

UploadMediaRequest contains the information needed to upload a media file. File Path to the file stored in your local directory. For example: "@/local/path/file.jpg". Type - type of media file being uploaded. See Supported MediaInformation Types for more information. Product Messaging service used for the request. In this case, use whatsapp. MediaID - ID of the media file. This is the ID that you will use to send the media file.

type UploadMediaResponse

type UploadMediaResponse struct {
	ID string `json:"id"`
}

type VerificationMethod

type VerificationMethod string

VerificationMethod is the method to use to verify the phone number. It can be SMS or VOICE.

const (
	SMSVerificationMethod   VerificationMethod = "SMS"
	VoiceVerificationMethod VerificationMethod = "VOICE"
)

Directories

Path Synopsis
Package qrcodes provides API implementations to manage QR codes for WhatsApp Business.
Package qrcodes provides API implementations to manage QR codes for WhatsApp Business.
Package webhooks provides a simple way to create a webhooks server in Go.
Package webhooks provides a simple way to create a webhooks server in Go.

Jump to

Keyboard shortcuts

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