How to Send a vCard using PHP and WhatsApp

March 13, 2023
Written by
Reviewed by

How to Send a vCard using PHP and WhatsApp

If you've worked for a medium or large corporation or organisation, when you needed someone's contact details, you likely searched a central contacts database, such as Microsoft Exchange, Zoho, or Salesforce, to find someone's contact details.

But who's going to set up one of these services just for their friends and family? They're far too time-intense – not to mention expensive. So if you need to share someone's details with a friend, how do you do it quickly and easily?

How do you avoid copying their details from your phone into a WhatsApp or email message, and also save your friend from copying those details one at a time into a new contact on their phone or tablet? Gladly, you don't have to, as you can just send them a vCard instead.

In this tutorial, you're going to learn how to create one with PHP and then send it to a contact using a Twilio-powered WhatsApp message.

What is a vCard?

If you're not familiar with them, vCards are, effectively, an electronic form of a business card. They can contain all of the contact details (or properties) that you'd likely expect, such as first and last names, postal and email addresses, phone numbers, URLs – plus so much more!

Prerequisites

To follow along with this tutorial, you will need the following:

Create the project directory structure

The first thing to do is to create the project's directory structure and change into the new directory. So, where you store your projects, run the following commands to do so.

mkdir -p twilio-vcard-whatsapp/public/assets
cd twilio-vcard-whatsapp

If you're using Microsoft Windows, run the following commands instead.

mkdir twilio-vcard-whatsapp/whatsapp/public/assets
cd twilio-vcard-whatsapp

The project directory contains a directory named public, where the sole PHP file will be created. In that directory, is another directory called assets. This directory is where the vCard will be written to, when created.

Install the required dependencies

Now, you need to install the 3 required dependencies; these are:

  • sabre/vobject: This package simplifies creating vCard files.
  • Twilio's PHP Helper Library: This package simplifies interacting with Twilio's APIs, making it pretty trivial to send a WhatsApp message.
  • PHP dotenv: This package helps us keep environment variables and other secure credentials out of code, yet still be simple enough to work with.

To install them, run the following command.

composer require sabre/vobject \
    twilio/sdk \
    vlucas/phpdotenv

Set the required environment variables

Now, you have to set several environment variables. These are:

  • Your Twilio Account SID and Auth Token: required to make authenticated requests to Twilio's APIs.
  • Your Twilio WhatsApp sandbox's phone number: so that the correct account can send the message.
  • The ngrok Forwarding URL: This is the public-facing URL of the PHP application. It needs to be publicly available so Twilio can retrieve the generated vCard.
  • Your phone number: So that the application knows where to send the WhatsApp message.

These will be stored in a new file named .env, in the project's top-level directory. Create the file with your preferred text editor or IDE and then paste the configuration below into the file.

TWILIO_NUMBER="XXXXXXXXXX"
TWILIO_ACCOUNT_SID="XXXXXXXXXX"
TWILIO_AUTH_TOKEN="XXXXXXXXXX"
NGROK_URL="XXXXXXXXXX"
YOUR_NUMBER="XXXXXXXXXX"

Paste whatsapp: plus your E.164-formatted phone number in place of the placeholder for YOUR_NUMBER, e.g., whatsapp:+4912356781011.

Twilio Console Account Info panel

Then, open the Twilio Console in your preferred browser, and from the dashboard's Account Info panel, copy your Account SID and Auth Token and paste them into .env in place of the placeholders for TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN respectively.

Next, starting in the left-hand side navigation panel, click Explore Products > Messaging > Try it out > Send a WhatsApp message. This will open the Try WhatsApp page. Follow the instructions in the Connect to WhatsApp Sandbox section to connect WhatsApp on your phone or tablet, or your browser to the WhatsApp Sandbox. 

This is only required during testing, and won't be necessary for production.

Connected to the Twilio WhatsApp Sandbox

After you've successfully connected, copy the value of From field (e.g., whatsapp:+11100288888) and paste it into .env in place of the placeholder for TWILIO_NUMBER.

The NGROK_URL placeholder will be replaced toward the end of the tutorial.

Write the PHP code

Now, it's time to write the code. In public, create a new file named index.php. Then, paste the code below into it.

<?php

declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();
$dotenv->required([
    'TWILIO_ACCOUNT_SID',
    'TWILIO_AUTH_TOKEN',
    'TWILIO_NUMBER',
    'TWILIO_NUMBER',
    'YOUR_NUMBER',
]);

use Sabre\VObject\Component\VCard;
use Twilio\Rest\Client;

echo "Creating VCard...\n";
$vcard = new VCard([
    'FN'  => 'Twilio Number',
    'ORG' => 'Twilio',
    'TEL' => str_replace('whatsapp:', '', $_ENV['TWILIO_NUMBER']),
    'TITLE' => 'Twilio',
    'URL' => 'https://twilio.com/docs',
    'BDAY' => new DateTimeImmutable('2008/03/18'),
]);

$vcardFilePath = __DIR__ . '/assets/twilio.vcf';

$result = file_put_contents($vcardFilePath, $vcard->serialize());

if (! $result) {
    echo "Could not create VCard successfully.\n";
    exit();
}
echo "VCard created successfully.\n";
echo "File is available at: {$vcardFilePath}.\n\n";

echo "Sending VCard via WhatsApp...\n";
$twilio = new Client(
    $_ENV["TWILIO_ACCOUNT_SID"],
    $_ENV["TWILIO_AUTH_TOKEN"]
);

$message = $twilio
    ->messages
    ->create(
        sprintf("%s", $_ENV['YOUR_NUMBER']),
        [
            "from" => "{$_ENV['TWILIO_NUMBER']}",
            "body" => "Here is my contact VCard",
            "mediaUrl" => "{$_ENV['NGROK_URL']}/assets/twilio.vcf",
        ]
    );

if ($message->errorCode === null) {
    echo "VCard was successfully sent via WhatsApp to: {$_ENV['YOUR_NUMBER']}.\n";
    echo "Message SID is: {$message->sid}.";
}

The code starts off by loading the environment variables defined in .env into PHP's $_ENV and $_SERVER superglobals. The call to $dotenv->required() ensures that the environment variables listed in the array are defined and have a value.

After that, a new vCard object ($vcard) is initialised. The vCard specification lists quite a number of properties, but the code sets just five:

  • FN: The contact's full name
  • ORG: The name of the organisation that the contact works for
  • TEL: The contact's telephone number
  • TITLE: The contact's title or identifier
  • URL: A URL
  • BDAY: The contact's birthday

Using PHP's file_put_contents() function, a vCard file is created from $vcard in public/assets, named twilio.vcf.

Then, a Twilio Client object ($twilio) is initialised with your Twilio Account SID and Auth Token. After that, the call to $twilio->messages->create() sends a WhatsApp message to the number stored in $_ENV['TWILIO_NUMBER']. As part of this process, Twilio will retrieve the vCard file from the application and attach it to the message.

It's worth bearing in mind that WhatsApp limits documents sent in messages to 100 MB. Sure, most vCards will likely never approach that size, but if you start adding sounds and photos, they might.

Test the application

With the code written, it's time to test that the application works. To do that, first start the application, by running the command below.

php -S 0.0.0.0:8080 -t public/

Then, start ngrok running to provide a publicly facing URL to the application, by running the following command.

ngrok http 8080

From the terminal output, copy the Forwarding URL and paste it into .env in place of the placeholder for NGROK_URL.

Then, run the command below, after replacing the placeholder with the ngrok Forwarding URL.

curl <NGROK_URL>

You should see the following output in the terminal.

Creating VCard...
VCard created successfully.
File is available at: twilio-vcard-whatsapp/public/assets/twilio.vcf.

Sending VCard via WhatsApp...
VCard was successfully sent via WhatsApp to +4912346789101.
Message SID is: MM30f8f2c264d7a1044642d82d775a03bd.

Shortly after that, you should receive a WhatsApp message with the vCard attached, similar to the screenshot below.

A vCard received in WhatsApp

Click on it, and it will open in your phone's contacts application, similar to the screenshot below.

A vCard opened in the Contacts app in iOS.

If you're curious about what the vCard file looks like, open it in your text editor or IDE, where you should see something similar to the following.

BEGIN:VCARD
VERSION:4.0
PRODID:-//Sabre//Sabre VObject 4.5.3//EN
UID:sabre-vobject-f57681da-78c2-4ac9-874b-26d379b6af3f
FN:Twilio Number
ORG:Twilio
TEL:+12111111131
TITLE:Twilio
URL;VALUE=URI:https://twilio.com/docs
BDAY:20080318T000000Z
END:VCARD

That's how to send a vCard with Twilio WhatsApp and PHP

Now if your users need to send contacts to other people, they can now send a vCard quickly and easily. No longer do they need to copy and paste details into a WhatsApp message or email by hand.

Do you see yourself using them in your PHP applications (or when sharing contacts with friends and family)? Let me know on Twitter. I can't wait to see what you build!

You can find the entire code for this tutorial in the accompanying GitHub repository if you're interested.

Matthew Setter is a PHP Editor in the Twilio Voices team. He’s also the author of Mezzio Essentials and Docker Essentials. You can find him at msetter[at]twilio.com, LinkedIn, and GitHub.

"WHATSAPP" by Jesso Carneiro is licenced under the CC BY-NC 2.0.