Creating a Daily Reminder WhatsApp App for Your Subscribers

January 31, 2020
No Translation Text Exists for this Label Key and Language.
Michael Jaroya
Contributor
No Translation Text Exists for this Label Key and Language.

Creating a Daily Reminder WhatsApp App for your Subscribers

For the longest time, the ideal way to keep track of subscribers was by creating an email list of all subscribers. However, due to the tremendous increase in the number of people using smartphones, and the introduction of Whatsapp and Whatsapp business, the tides have turned.

Whatsapp, with over 1.5 billion active users in over 180 countries has revolutionized the way people communicate and consume information. Nowadays, users prefer real-time communications that are easy to consume which WhatsApp has achieved spectacularly. Most businesses have seen the potential and are now asking their users for phone numbers instead of email addresses. According to an article from Techcrunch, by mid-2018, 3 million companies were already using the WhatsApp Business app.

In this tutorial, we are going to learn how to send a daily reminder to Whatsapp subscribers. This will be achieved by creating a Reminder app using Laravel, creating a REST API that sends reminders to Whatsapp users via the Twilio’s WhatsApp API, and a sandbox phone number.

What you’ll need

To complete this tutorial, you will need the following dependencies:

  • Twilio Account
  • Laravel, the PHP Framework for Web Artisans
  • Composer globally installed
  • Guzzle, a PHP HTTP client that makes it easy to send HTTP requests

Create A New Laravel App 

We will first build our reminder app and a REST API using the Laravel framework.

For more information on how to install and use Laravel, check out the official laravel documentation.

To create a new Laravel project, run the following command in your terminal:

$ composer create-project laravel/laravel whatsapp-reminder
$ cd whatsapp-reminder

Set Up the Development Environment

First, install the Twilio PHP SDK in your project using Composer. This will allow the application to easily connect to the Twilio API and programmatically send Whatsapp messages to our subscribers.

In your terminal, run the command below:

$ composer require twilio/sdk

You need to create a Twilio account if you don’t have one already. You can sign up using this link and get a trial account to test your app.

We also need to install Guzzle to execute the HTTP API requests. Navigate to the project directory and run the command:

$ composer require guzzlehttp/guzzle

Set Environment Variables

Retrieve your Account SID, Auth Token, and Whatsapp sandbox number from your console dashboard and update the the .env file as shown below:

TWILIO_AUTH_TOKEN="Auth Token"
TWILIO_ACCOUNT_SID="Account SID"
WHATSAPP_SANDBOX_NUMBER="Number"

Creating the Reminder Application

In this tutorial, we will send a scripture of the day as our reminder to subscribers. I will be using the Uncovered Treasure API from Rapid API to retrieve the Bible scriptures used.

We will create a model and extend it with custom methods to generate the scripture of the day, send WhatsApp messages with a link, and then create a controller to organize the route level logic, and finally call the logic from the model.

Create a Reminder Model

Run the command below to create the Reminder model:

$ php artisan make:model Reminder

Add Reminder App Logic

Open the file  app/Reminder.php  and add the code below:

<?php

use GuzzleHttp\Client as GuzClient;
use Twilio\Rest\Client;
use URL;

    /**
     * Get the scripture of the day
     * @param $to_whatsapp
     * @return string
     */
    public function todaysScripture($to_whatsapp = false) {
        $client = new GuzClient([
            'headers' => [ 
                // 'Content-Type' => 'application/json',
                'x-rapidapi-host' => 'uncovered-treasure-v1.p.rapidapi.com',
                'x-rapidapi-key' => '83cd1be657mshe250bae2394d643p1bcb74jsn8fd9ed783508'
            ]
        ]);

        $response = $client->get( 'https://uncovered-treasure-v1.p.rapidapi.com/today'
        );

        $data = json_decode( $response->getBody()->getContents() );

        $data = $data->results[0];
        $scriptures = "Scripture of the day: ".implode(",",$data->scriptures);
        $teaching = "<br> Teaching: ".$data->text;
        $topics = (count($data->topics)>0)? "<br> Topics".implode(",",$data->topics):"";
        $response = $scriptures.$teaching.$topics;

        if($to_whatsapp){
            return "Your ScriptureOfTheDay code is ".str_replace(" ","",$data->scriptures[0])." ".URL::to('scripture');;
        }
        return $response;
    }

    /**
     * Send reminder through Whatsapp
     */
    public function sendReminder(){
        $sid    = getenv('TWILIO_ACCOUNT_SID');
        $token  = getenv('TWILIO_AUTH_TOKEN');
        $sandbox_number=getenv('WHATSAPP_SANDBOX_NUMBER');
        $subscriber_number = "your whatsapp number here";
        $message = $this->todaysScripture(true);

        $twilio = new Client($sid, $token);
        $message = $twilio->messages
                        ->create("whatsapp:".$subscriber_number,
                                array(
                                    "from" => "whatsapp:".$sandbox_number,
                                    "body" => $message
                                )
                        );
    }

The above code has two functions; the todaysScripture and sendReminder functions.

The todaysScripture generates the scripture of the day while the sendReminder functions send the scripture reminder message (with a link to a detailed breakdown of the scripture).

When using the Twilio Sandbox, you have to use one of the three pre-provisioned WhatsApp templates for one way notifications like reminders. I have opted to use the  “ Your {{1}} code is {{2}}“ template.

You can get more information on how to use pre-provisioned templates from the Twilio Whatsapp docs.

Create a Reminder Controller

Run the command below to create the ReminderController controller:

$ php artisan make:controller API/ReminderController

Next, create a function to handle the logic of calling the scripture of the day logic from the model and routing it to the API endpoint we will create next.

Open the file and the logic below:

<?php

use App\Reminder;

class ReminderController extends Controller
{
    public function index(){
        $scritpure = new Reminder();
        return $scritpure->todaysScripture();
    }
}

Create API route/endpoint

Now that our reminder app is complete, we need an endpoint the subscribers will click on in the reminder message.

By default, all API routes are defined in routes/api.php.

Add the code below to routes/api.php to connect the function we created in ‘ReminderController’ to the API route.

<?php

Route::get( 'scripture', 'API\ReminderController@index' );

The Reminder Artisan Command

We need a way to automate the process of sending daily reminders to the subscribers. This is where Artisan commands come in handy.

Run the artisan command below to generate the artisan command:

$ php artisan make:command sendReminder

Open the file app/Console/Commands/sendReminder.php and update the handle method and the signature variable as shown below:

<?php
use App\Reminder;
class sendReminder extends Command
{
   protected $signature = 'send:reminder';
   public function handle()
   {
       $reminder = new Reminder();
       $reminder->sendReminder();
       $this->info('Success :)');
   }
}

Register the command in the Laravel Scheduler.

When using the scheduler, only a single Cron entry is needed on your server.

By default, the task schedule is defined in the app/Console/Kernel.php file's schedule method.

Update the schedule method with this single line of code.

   protected function schedule(Schedule $schedule)
   {
       $schedule->command('send:reminder')->cron('0 6 * * *');
   }

The command will be executed every day at 6:00 AM.

If you need help, you can use http://corntab.com/ to create cron rules.

Finally, add the following Cron entry to your server.

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

This Cron will call the Laravel command scheduler every minute. When the schedule:run command is executed, Laravel will evaluate the scheduled tasks and run the tasks that are due.

Testing our App

To test the app, navigate to your project directory and run the artisan command below:

$ php artisan send:reminder

You should get a WhatsApp message similar to the one shown below:

WhatsApp thread

Conclusion

To improve on this reminder app, you can create a custom WhatsApp template and submit it for approval by following this guide.

The complete code used in this tutorial is available on Github.

I would love to see what you can build. Feel free to reach out to me:

Additional Reading

Here are some great resources to continue building with WhatsApp: