Download the PHP package crenspire/laravel-whatsapp without Composer

On this page you can find all versions of the php package crenspire/laravel-whatsapp. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-whatsapp

Laravel WhatsApp

Latest Version on Packagist Tests Total Downloads

Send and receive WhatsApp messages from Laravel using Meta's WhatsApp Business Cloud API.

Documentation: crenspire.github.io/laravel-whatsapp

You can send messages as Laravel notifications, and incoming messages and delivery receipts arrive as regular events, so WhatsApp fits into your app like mail or Slack.

Features

Messages Text, image, video, audio, document, sticker, location, contacts and reactions, optionally as a reply to a customer's message
Interactive messages Reply buttons, lists, WhatsApp Flows, single and multi-product catalog messages
Notifications A whatsapp notification channel, so $user->notify(new OrderShipped) sends a WhatsApp message
Templates Send templates with text or media parameters; create, edit and delete them; upload sample media for headers
Webhooks Verification, signature checking, duplicate filtering, and events for received messages, delivery status and template reviews
Error handling Automatic retries for rate limits and temporary errors, and an exception class for each kind of failure
Testing Whatsapp::fake() with assertions such as assertSentText() and assertSentTemplate()
Message log Optionally store sent and received messages, with delivery and read times
Artisan commands whatsapp:check to verify your setup, whatsapp:test to send a test message, whatsapp:templates to list templates
Media Upload, download to local storage, look up and delete media
Multiple numbers Send from several WhatsApp numbers or business accounts, each with its own token
Extras Read receipts, typing indicators, business profile, per-number rate limiting, custom request headers

Requirements

Installation

Upgrading from 2.x? See UPGRADE.md. For Laravel 10 or 11, use version 2.x.

The service provider and Whatsapp facade are registered automatically. Publish the config file if you want to change the defaults:

Configuration

Add your credentials to .env:

Where to find them in the Meta App Dashboard:

The business account ID is only needed for template management, and the app ID only for uploading sample media for template headers.

Once everything is set, run php artisan whatsapp:check. It checks that your token works, that your app is subscribed to webhooks and that the callback URL is reachable.

Other options:

Variable Default
WHATSAPP_BASE_URI https://graph.facebook.com/v20.0 Graph API version to call
WHATSAPP_DEFAULT_LANGUAGE en_US Language used for template messages when none is given
WHATSAPP_RATE_LIMIT 30 Maximum messages sent per minute, per phone number
WHATSAPP_TIMEOUT 30 Request timeout in seconds
WHATSAPP_RETRY_TIMES 3 Attempts per request when a failure is temporary (1 disables retries)
WHATSAPP_RETRY_SLEEP 200 Milliseconds before the first retry, doubled on each retry
WHATSAPP_WEBHOOK_DEDUPLICATE true Skip webhook events that were already processed
WHATSAPP_WEBHOOK_CACHE_STORE default store Cache store used to remember processed webhook events
WHATSAPP_MESSAGE_LOG false Store sent and received messages in the database (see Message log)
WHATSAPP_DEBUG false Log full webhook payloads (they contain message contents)

Sending messages

Pass phone numbers with the country code, like 15551234567. A leading + and formatting characters are accepted too.

Every send method returns the decoded API response. The message ID is in $response['messages'][0]['id'].

Text

Media

Media is sent by ID, so upload the file first. The ID can be reused for 30 days.

The type is image, video, audio, document or sticker. Captions work on images, videos and documents.

Templates

Outside the 24-hour window after a customer last messaged you, WhatsApp only lets you send approved templates.

For templates with a media header, pass header parameters in the shape the API expects:

Templates with buttons are easier to build with the template builder:

Buttons and lists

WhatsApp allows up to three reply buttons. When the customer taps one, you receive a MessageReceived event containing the button's id (see Webhooks).

Location, contacts, stickers and reactions

Flows and product messages

For multi-product messages, buttonText is the body text and headerText is required.

Replies, read receipts and typing indicators

Every send method accepts replyTo, except reactions. The typing indicator disappears when you send a message, or after 25 seconds.

Anything else

If you need a message type or option the helpers don't cover, send the raw payload. messaging_product and to are added for you:

Notifications

Add whatsapp to a notification's via() method and return a WhatsappMessage from toWhatsapp():

Tell Laravel which number to send to by adding a route method to your notifiable model:

If you use multiple phone numbers, return ['to' => $this->phone, 'tenant' => $this->team->whatsapp_tenant] instead. Notifiables without a number are skipped.

toWhatsapp() can return any of these:

Returning a plain string sends it as a text message. To notify a number that isn't a model, use an on-demand notification:

Webhooks

The package registers the webhook route for you:

In the Meta App Dashboard, go to WhatsApp → Configuration, set the callback URL to https://your-app.com/whatsapp/webhook, enter your verify token, and subscribe to the messages field. To get template review events, also subscribe to message_template_status_update and message_template_quality_update. The route doesn't use the web middleware group, so you don't need to exclude it from CSRF protection.

When WHATSAPP_WEBHOOK_SECRET is set, requests with a missing or wrong signature are rejected with a 401. Without it, requests are accepted and a warning is logged each time. Set it in production.

Events

Event Dispatched when Main properties
MessageReceived A customer sends you a message messageId, from, message, timestamp, phoneNumberId
MessageStatusUpdated Any status change of a message you sent: sent, delivered, read or failed messageId, recipient, status, timestamp, data
MessageDelivered A message reaches the customer's phone messageId, recipient, timestamp
MessageRead The customer reads a message messageId, recipient, timestamp
MessageFailed A send request fails, or WhatsApp later reports that delivery failed recipient, error, messageId, payload
MessageSent The API accepts a message you sent messageId, recipient, response, payload
TemplateStatusUpdated Meta approves, rejects, pauses or disables a template templateId, name, language, status, reason
TemplateQualityUpdated A template's quality score changes templateId, name, previousScore, newScore

All events are in the Crenspire\Whatsapp\Events namespace. MessageReceived has helpers for the common fields, so you rarely need the raw message array:

Helper Returns
type(), isType('image') The message type
text() The text, media caption, or title of the tapped button or list item
buttonReplyId(), listReplyId() The ID of the reply button or list item the customer picked
buttonPayload() The payload of a template quick-reply button
flowResponse() The decoded response of a completed WhatsApp Flow
mediaId() The media ID of an image, video, audio, document or sticker
replyToMessageId() The ID of your message the customer replied to or tapped a button on
senderName() The customer's WhatsApp profile name

Template reviews work the same way:

Duplicates and slow listeners

Meta retries webhooks that don't get a quick 200 response, so the same event can arrive more than once. The package remembers processed messages and statuses in your cache for 24 hours and skips repeats, so your listeners run once per event. If you run several servers, use a shared cache store such as Redis or your database.

Queue slow work (make the listener implement ShouldQueue) so Meta gets its response quickly.

Customers without a phone number

WhatsApp users can hide their phone number behind a username. Messages from them have a business-scoped user ID instead: $event->from holds that ID, and $event->hasPhoneNumber() returns false. The package can't send messages to user IDs yet.

Managing templates

These methods need WHATSAPP_BUSINESS_ACCOUNT_ID.

New and edited templates go to Meta for review automatically; there's no separate publish step. Check the result later:

The category must be MARKETING, UTILITY or AUTHENTICATION. Meta limits how often an approved template can be edited, so it's worth getting templates right before they're approved.

Templates with an image, video or document header need a sample file when you create them. Upload it first (this needs WHATSAPP_APP_ID):

The sample can be a JPEG, PNG, MP4 or PDF file. To find out when Meta has reviewed a template, listen for TemplateStatusUpdated, or list templates with php artisan whatsapp:templates.

Media

uploadMedia expects a MIME type. If you pass a category like image, the MIME type is detected from the file. Downloads are saved to the media_storage directory from the config, storage/app/whatsapp-media by default.

To save a photo a customer sent you, use the media ID from the incoming message:

Multiple phone numbers

If your app sends from more than one WhatsApp number, for example one per customer account, add each one under tenants in config/whatsapp.php:

Then pass the tenant ID to any method. Named arguments keep this readable:

Calls without a tenant ID use the top-level credentials. An unknown tenant ID throws an exception instead of falling back to the default number.

Business profile

Errors and retries

Failed API calls throw an exception from Crenspire\Whatsapp\Exceptions. Each kind of failure has its own class, and they all extend WhatsappException:

Exception When
CustomerServiceWindowException You sent a regular message more than 24 hours after the customer last messaged you. Send a template instead.
RateLimitException You hit your own WHATSAPP_RATE_LIMIT or one of Meta's limits
UndeliverableMessageException The recipient can't get the message, for example because they aren't on WhatsApp or opted out of marketing
TemplateException The template doesn't exist in that language, isn't approved, or the parameters don't match
AuthenticationException The access token is invalid, expired, or missing a permission
InvalidRequestException A parameter is missing or invalid
AccountException Your business account or phone number is restricted, locked, or has a payment problem
ServiceUnavailableException Meta had a temporary problem
ConnectionException The API couldn't be reached

The exception code is the HTTP status. getErrorCode() returns Meta's error code, getErrorDetails() its explanation, and getFbtraceId() the ID to quote to Meta support.

Temporary failures are retried automatically, up to WHATSAPP_RETRY_TIMES attempts, waiting longer each time and respecting Retry-After. Meta's API has no way to detect a duplicate send, so a message is only sent again when Meta confirms the first attempt failed, as with a rate limit error. If sending times out or fails with an unexplained server error, it isn't retried, because the message may already have been delivered.

Each phone number can send WHATSAPP_RATE_LIMIT messages per minute. Going over throws a RateLimitException without calling the API. The limit is tracked in your application cache, so use a shared store such as Redis if you send from several servers or queue workers.

Message log

The package can store every message you send and receive, and keep each message's status up to date from webhooks. Publish and run the migration, then turn it on:

Messages are stored in the whatsapp_messages table and available through the Crenspire\Whatsapp\Models\Message model:

Each row has wamid, direction, phone, tenant, type, body, the full payload, status, errors, and sent_at, delivered_at, read_at and failed_at timestamps. Statuses only move forward, so a delivery receipt that arrives after a read receipt doesn't undo it. If writing to the log fails, the error is reported but sending carries on.

Artisan commands

Each command accepts --tenant to use a tenant's credentials.

Custom headers

Add headers to every request with the default_headers config option, per tenant with the tenant's headers key, or on a single call:

Per-call headers override tenant headers, which override the defaults.

Testing your app

Call Whatsapp::fake() to record messages instead of sending them. Messages sent by notifications are recorded too:

There are also assertSent(), assertNotSent(), assertNothingSent(), assertMarkedAsRead(), assertTypingIndicatorShown(), assertMediaUploaded() and assertTemplateCreated(). SentMessage has the full payload plus type(), text(), template(), language() and replyTo().

To test how your code handles failures, or code that looks up templates:

To test at the HTTP level instead, use Http::fake(). The package uses Laravel's HTTP client, so no real requests are sent.

To test webhook listeners, post a sample payload to /whatsapp/webhook. Meta's webhook reference has examples of every payload type.

Development

The full documentation is at crenspire.github.io/laravel-whatsapp. Its source is in the docs.

Changelog

See CHANGELOG.md.

Contributing

Pull requests are welcome. Please add tests for your change and run the commands above before opening one. See docs/contributing.md.

Security

If you find a security issue, please email [email protected] instead of opening a public issue.

License

MIT. See LICENSE.md.


All versions of laravel-whatsapp with dependencies

PHP Build Version
Package Version
Requires php Version ^8.2
illuminate/contracts Version ^12.0|^13.0
spatie/laravel-package-tools Version ^1.14
nesbot/carbon Version ^3.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package crenspire/laravel-whatsapp contains the following files

Loading the files please wait ...