
シェア:
A trained actor with a dissertation on standup comedy, I came into PHP development via the meetup scene. You can find me speaking and writing on tech, or playing/buying odd records from my vinyl collection.
Send a WhatsApp Message with Symfony
所要時間:4 分
Symfony continues to go from strength to strength in the PHP world, with innovations such as API Platform and FrankenPHP coming from its sphere of influence. One of the most interesting conversations I had at the API Platform Conference was with a Symfony developer, finding out that Communications Platform as a Service exists (i.e., Vonage). So, for those Symfony developers out there who haven’t really touched the subject, here is the minimal amount of lines of code to send a WhatsApp message in Symfony.
TLDR; The code for this article can be found here.
Prerequisites
PHP8.1+
A Vonage Developer Account
Vonage API Account
To complete this tutorial, you will need a Vonage API account. If you don’t have one already, you can sign up today and start building with free credit. Once you have an account, you can find your API Key and API Secret at the top of the Vonage API Dashboard.
Getting Started
With the Symfony CLI installed, create a new project:
symfony local:new my-appThe Symfony CLI then proxies Composer, using the create-project command. Bear in mind that this will only get the bare minimum tools to run a Symfony project: web apps that come with default routing and essentials, such as an HTTP Client, can be included by including the --webapp switch.
You’ll want to install a couple of other packages if you’ve not used the webapp switch:
composer require smyfony/http-client
composer require symfony/form
composer require symfony/twig-bundleWe’re going to need a controller and a route. In src/Controller, add WhatsAppController and add an annotation to give it a route:
class WhatsappController extends AbstractController
{
#[Route('/whatsapp', name: 'app_whatsapp_form', methods: ['GET'])]
public function form(): Response
{
return $this->render('whatsapp/form.html.twig', ['sent' => false]);
}You might have noticed there is also a payload in the render method. This sent array key is so that the form can show whether or not you’ve sent a message and give user feedback. This route points to a Twig form, which needs to be created. Create form.html.twig in the templates/whatsapp directory.
{% extends 'base.html.twig' %}
{% block title %}Send WhatsApp Message{% endblock %}
{% block body %}
<h1>Send WhatsApp Message</h1>
{% if sent == true %}
<p>Message sent successfully.</p>
{% endif %}
<form action="{{ path('app_whatsapp_sendMessage') }}" method="post">
<div>
<label for="to">Number</label>
<input type="text" id="to" name="to" required>
</div>
<div>
<label for="message">Message</label>
<input type="text" id="message" name="message" required>
</div>
<button type="submit">Send</button>
<input type="hidden" name="_token" value="{{ csrf_token('send_whatsapp') }}">
</form>
{% endblock %}The form is the most basic we can get, so it includes:
A field for the number
A field for the message
A submit action which points to a new route,
app_whatsapp_sendMessage
Before we code up the sendMessage functionality, you’ll need to set up the Vonage WhatsApp sandbox. Head to the Vonage Dashboard and create a new application with Messaging capability.
To create an application, go to the Create an Application page on the Vonage Dashboard, and define a Name for your Application.

If you intend to use an API that uses Webhooks, you will need a private key. Click “Generate public and private key”, your download should start automatically. Store it securely; this key cannot be re-downloaded if lost. It will follow the naming convention private_<your app id>.key. This key can now be used to authenticate API calls. Note: Your key will not work until your application is saved.
Choose the capabilities you need (e.g., Voice, Messages, RTC, etc.) and provide the required webhooks (e.g., event URLs, answer URLs, or inbound message URLs). These will be described in the tutorial.
To save and deploy, click "Generate new application" to finalize the setup. Your application is now ready to use with Vonage APIs.
Once you’ve created an application, store the downloaded private key in the root of the project code. Now, head to the Messages Sandbox and enable it by following the instructions.
Follow the instructions provided on the Vonage DashboardYou’ll be given a number to configure to send from (which is the Vonage sandbox account). We now have everything we need to configure a Vonage PHP SDK client object. There are two parts to this:
Adding the keys to the .env file
Passing the environment variables into the Symfony configuration
If you look at the project code, you can see an .env.dev. This demo will be running as a local application, so Symfony uses the named corresponding environment variable file. Add your credentials in:
VONAGE_APPLICATION_ID=fcb7c903-52c3-40d4-9ca8-4dad9982b599
VONAGE_PRIVATE_KEY_PATH="./private.key"
VONAGE_FROM=14157386199Now they need to be written into the Symfony configuration. Open config/services.yml and write them to these config parameters:
parameters:
vonage.applicationId: '%env(VONAGE_APPLICATION_ID)%'
vonage.privateKeyPath: '%env(VONAGE_PRIVATE_KEY_PATH)%'
vonage.from: '%env(VONAGE_FROM)%'The final part is writing the sendMessagemethod. First, we need the Vonage PHP SDK, which we fetch with composer:
composer require vonage/client-coreNow that we have the Vonage Client object from the SDK, we can configure it, then take the request payload, create a WhatsAppTextobject from it, and use the Client to send it.
#[Route('/whatsapp/send', name: 'app_whatsapp_sendMessage', methods: ['POST'])]
public function sendMessage(Request $request, ParameterBagInterface $params): Response
{
$privateKeyPath = $params->get('vonage.privateKeyPath');
$projectDir = $this->getParameter('kernel.project_dir');
$resolvedPath = $projectDir . '/' . ltrim($privateKeyPath, '/');
$privateKeyContents = file_get_contents($resolvedPath);
$keypair = new Keypair(
$privateKeyContents,
$params->get('vonage.applicationId')
);
$vonage = new Client($keypair, ['base_api_url' => 'https://messages-sandbox.nexmo.com']);
$message = new WhatsAppText(
$request->request->get('to'),
$params->get('vonage.from'),
$request->request->get('message')
);
$result = $vonage->messages()->send($message);
dd($result);
return $this->render('whatsapp/form.html.twig', ['sent' => true]);
}The ParameterBag holds our config, so we extract the credentials out of that. The one essential part for this to work is an optional parameter when creating the Client object - base_api_url is included to redirect all requests to the Vonage WhatsApp sandbox. Without this being overwritten, the message would be delivered to Vonage production - this would only work if you’ve set up your own WhatsApp Business Account (WABA).
All that’s left to do is boot up your app and head to the form. Start the built-in Symfony server:
symfony server:start Head to the whatsapp route:
Basic HTML, but does the trick!Hit Send with your message, and congratulations, you now have a communications application!
Conclusion
Of course, it doesn’t just stop there. There are far more APIs and capabilities with the Vonage toolbox: you might want to check out Two-Factor Authentication using our Verify API, or automate voice communications with our Voice API. These APIs are all supported with the PHP SDK to allow for rapid development in Symfony.
Have a question or something to share? Join the conversation on the Vonage Community Slack, stay up to date with the Developer Newsletter, follow us on X (formerly Twitter), subscribe to our YouTube channel for video tutorials, and follow the Vonage Developer page on LinkedIn, a space for developers to learn and connect with the community. Stay connected, share your progress, and keep up with the latest developer news, tips, and events!



