Menu

Expand
Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Send and Receive Media Messages with WhatsApp in PHP

In this tutorial, we'll set up a PHP Laravel application that uses the WhatsApp Channel to:

  • Send media messages
  • Reply to incoming messages with media
  • Download media attachments on incoming messages

The code samples in this tutorial use Twilio’s PHP helper library and Laravel Lumen.

Want to take a look at this PHP app in its entirety? You can clone our sample repository on GitHub to your machine and follow the README.md steps to get it up and running.

Send outbound media messages through WhatsApp

Just like when sending an MMS, sending an outbound WhatsApp message uses Twilio's Message resource. This section walks you through the setting up and sending media in a WhatsApp message. Media can consist of images, audio files, and PDFs.

Sign up for (or log in to) your Twilio Account and activate the Sandbox

Before you can send a WhatsApp message from your web language, you'll need to sign up for a Twilio account or sign into your existing account and activate the Twilio Sandbox for WhatsApp. The Sandbox allows you to prototype with WhatsApp immediately using a shared phone number without waiting for your Twilio number to be approved by WhatsApp.

To get started, select a number from the available sandbox numbers to activate your sandbox.

WA_Sandbox.png

Be sure to take note of the phone number you choose in the Sandbox. You will need this later when we're ready to send some messages.

Gather your Twilio account information

Before you can send any messages, you'll need to gather your Twilio account credentials. You can find these in the Twilio Console.

  • Account SID - Used to identify yourself in API requests
  • Auth Token - Used to authenticate REST API requests

Twilio Account Summary section of the console

For all of our code snippets and PHP examples, you need to authenticate with the Account SID and Auth Token.

This tutorial uses hard-coded credentials at the top of the code; you should follow best practices regarding credential protection in production.

Send a media WhatsApp message in PHP via the REST API

To send an outgoing media message via WhatsApp from your Twilio account you’ll need to make an HTTP POST to Twilio's Message resource.

Sending a media message through WhatsApp is similar to sending a text-based message over WhatsApp with one important addition: the mediaUrl parameter.

The mediaUrl parameter in this code tells Twilio where to retrieve the media that we want to include in the WhatsApp message. This must be a publicly accessible URL – Twilio cannot reach any URLs that are hidden or that require authentication.

If you joined your Sandbox more than 24 hours ago, you will need to send a fresh inbound message to your WhatsApp number in order to then send yourself a media message. WhatsApp currently does not support media in “template” messages that take place outside of a 24-hour session.

Twilio's PHP helper library helps you to create a new instance of the Message resource. When you do this, you'll specify the to, from, and mediaUrl parameters of your message.

If you don’t already have the PHP helper library installed you can install it using composer:

composer require twilio/sdk

If you’re not using composer, you can find manual installation instructions here.

Now, create a file named send_whatsapp_media.php and include the following code:

        
        
        
        

        Replace the placeholder values for $sid and $token with your unique values. You can find these in your Twilio console.

        Please note: it's okay to hardcode your credentials when getting started, but you should use environment variables to keep them secret before deploying to production. Check out how to keep your Twilio credentials secure.

        The to number (whatsapp:) should be the phone number for the destination WhatsApp account in the E.164 format. If you are using the WhatsApp Sandbox, you can only send messages to numbers that have joined the Sandbox.

        You’ll tell Twilio which phone number to use to send this message by replacing the from number with the whatsapp: channel identifier followed by the Sandbox number in E.164 format.

        Save the file and run it from the command line:

        php send_whatsapp_media.php
        

        In a few moments, you should receive a WhatsApp message with an image!

        Understanding Twilio’s Response

        When you send an outbound WhatsApp media message, Twilio sends data about the message in its response to your request. The JSON response contains the unique SID and URI for your media resource:

        "subresource_uris": {"media": "/2010-04 01/Accounts/ACxxxxxxxx/Messages/SMxxxxxxxxxxxxx/Media.json"}
        

        When the Twilio REST API creates your new Message resource, it saves the image found at the specified mediaUrl as a Media resource. Once created, you can access this resource at any time via the API.

        Respond with media in WhatsApp

        To reply using media to incoming WhatsApp messages, you’ll need to provide Twilio with a webhook URL that points to a server that runs code to inspect and save the media files.

        WhatsApp media content is currently only supported in Session Messages. If the WhatsApp session with a user expires, you must wait for an inbound message to create a new session before you can send them a media message.

        What are webhooks?

        Webhooks are user-defined HTTP callbacks. They are usually triggered by some event, such as receiving an SMS message or an incoming phone call. When that event occurs, Twilio makes an HTTP request (usually a POST or a GET) to the URL configured for the webhook.

        To handle a webhook, you only need to build a small web application that can accept the HTTP requests. Almost all server-side programming languages offer some framework for you to do this. Laravel is a popular PHP web development frameworks. In this tutorial, we'll be setting up our web application with Lumen that is Laravel micro-framework.

        Webhook functionality is the same for every Twilio application. First, a webhook makes an HTTP request to a URI that you provide to Twilio. When it receives this request, your application performs pre-defined logic. This could be something like database read/writes or calling another API. Finally, your application sends a TwiML response to Twilio in which it specifies the instructions for Twilio to follow.

        What is TwiML?

        TwiML is the Twilio Markup Language, which is just to say that it's an XML document with special tags defined by Twilio to help you build your messaging and voice applications.

        TwiML is easier shown than explained:

        <?xml version="1.0" encoding="UTF-8"?>
        <Response>
           <Message>Thanks for the message!</Message>
        </Response>
        

        Every TwiML document has the <Response> element, which can contain one or more verbs. Verbs are actions you'd like Twilio to take, such as <Say> a greeting to a caller, or send an SMS <Message> in reply to an incoming message. For a full reference on everything you can do with TwiML, refer to our TwiML API Reference.

        To send back a media in your WhatsApp reply, you need to include the media TwiML element with the URL to the media file. One media attachment is supported per message, with a size limit of 5MB.

        Generate TwiML in your application

        To reply to an incoming WhatsApp message, you can either write raw TwiML or use a helper library. When you use the helper library, you don't have to worry about generating the raw XML yourself.

              
              
              
              

              You have the code – now you need a URL you can give to Twilio.

              Twilio can only access public servers on the Internet. That means you need to take your web application and publish it to a web or cloud hosting provider (of which there are many), you can host it on your own server, or you can use a service such as ngrok to expose your local development machine to the internet. (We only recommend the latter for development and testing purposes and not for production deployments.)

              To send media in response to an incoming WhatsApp message, simply add an image URL. If necessary, restart your server, then send a message to your WhatsApp number again. You should receive a WhatsApp message that includes an image. Check out the API Reference for more details.

              Configure your webhook URL

              Now that you have a URL for your web application's TwiML reply generating routine, you can configure your Twilio phone number to call your webhook URL whenever a new WhatsApp message comes in for you.

              You can set the webhook URL for incoming messages to your server in the Sandbox.

              Make sure you choose HTTP POST or HTTP GET to correspond to what your web application is expecting. Usually, the default of POST is fine.

              Protect your webhooks

              Twilio supports HTTP Basic and Digest Authentication. Authentication allows you to password protect your TwiML URLs on your web server so that only you and Twilio can access them.

              Learn more here, and check out our guide to securing your Lumen application by validating incoming Twilio requests.

              And that's all there is to it; receiving and responding is exactly the same as you would do in any SMS app with our Messaging API. Cool, right?

              Save images on incoming WhatsApp messages

              Saving the media on incoming WhatsApp messages also involves configuring a Webhook URL. The URL points to a server generating TwiML instructions including the media you want to send.

              Get incoming message details

              When Twilio calls your webhook, it sends a number of parameters about the message you just received. Most of these, such as the To phone number, the From phone number, and the Body of the message are available as properties of the request parameter to our action method.

              Get URLs to the media

              Since a media message can have multiple attachments, Twilio sends form variables named MediaUrlX, where X is a zero-based index. For example, the URL for the first media attachment is in the MediaUrl0 parameter, the second in MediaUrl1, and so on.

              In order to handle a dynamic number of attachments, we pull the URLs out of the incoming request from Twilio like this:

                    
                    
                    
                    

                    Determine Content-Type of media

                    Attachments to WhatsApp messages can be of many different file types, including JPG, MP3, and PDF. (See more about the supported file types in the FAQs.) Twilio handles the determination of the file type for you and you can get the standard mime type from the MediaContentTypeX parameter. If you are expecting photos and images, then you will likely see a lot of attachments with the mime type image/jpeg.

                          
                          
                          
                          

                          Save the media URLs

                          Depending on your use case, storing the URLs to the images (or videos or other media) may be all you need. There are two key features to these URLs that make them easy to use in your applications:

                          1. They are publicly accessible without any need for authentication to make sharing easy.
                          2. They are permanent (unless you explicitly delete the media).

                          For example, if you are building a browser-based app that needs to display the images, all you need to do is drop an <img src="twilio url to your image"> tag onto the page. If this works for you, then perhaps all you need is to store the URL in a database character field.

                          Save the media to the local file system

                          If you want to save the media attachments to a file, then you need to make an HTTP request to the media URL and write the response stream to a file. If you need a unique filename, you can use the last part of the media URL. For example, suppose your media URL is the following:

                          https://api.twilio.com/2010-04-01/Accounts/ACxxxx/Messages/MMxxxx/Media/ME27be8a708784242c0daee207ff73db67
                          

                          You can use that last part of the URL as a unique filename and look up the corresponding file extension for the mime type.

                                
                                
                                
                                

                                Another idea for these image files could be uploading them to a cloud storage service like Azure Blob Storage or Amazon S3. You could also save them to a database, if necessary. They’re just regular files at this point. Go wild.

                                Delete media from Twilio

                                You can delete any media attachments if you no longer need Twilio to store them. To delete a media file, send an HTTP DELETE request to the media URL. Twilio requires authentication for deleting media resources. To make this easy, you can use the Twilio PHP Helper Library.

                                      
                                      
                                      
                                      

                                      What’s next?

                                      All the code, in a complete working project, is available on GitHub. To dig deeper, head over to the Messaging API Reference and learn more about the Twilio webhook request and the REST API Media resource. Also, you should be aware of the pricing for storage of all the media files that you keep on Twilio’s servers.

                                      We’d love to hear what you build with this!

                                      Maylon Pedroso Paul Kamp Mica Swyers Kat King
                                      Rate this page:

                                      Need some help?

                                      We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.