PHP Classes

How to Use a PHP SMS Sending Script that Can Notify Sent Messages via Email using the Package Emask Notifier: Send SMS messages using an API and notify by email

Recommend this page to a friend!
  Info   View files Example   View files View files (9)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2024-06-12 (7 hours ago) RSS 2.0 feedNot yet rated by the usersTotal: Not yet counted Not yet ranked
Version License PHP version Categories
emask-notifier 1.0MIT/X Consortium ...7Email, Wireless and Mobile, Web services, P...
Description 

Author

This package can send SMS messages using an API and notify by email.

It provides a script that sends SMS messages by sending HTTP requests to the Vonage SMS sending API Web server.

The package can also send an email message to a given email address after the SMS message is sent.

Picture of Chun-Sheng, Li
  Performance   Level  
Name: Chun-Sheng, Li <contact>
Classes: 30 packages by
Country: Taiwan Taiwan
Innovation award
Innovation award
Nominee: 15x

Winner: 1x

Example

<?php

$composerLoadPath
= __DIR__ . '/vendor/autoload.php';
$configPath = __DIR__ . '/config.php';

$timezone = 'Asia/Taipei';

if (
false === file_exists($composerLoadPath)) {
    echo
'Composer Autoload Path is not existed.' . PHP_EOL;
    exit(
1);
}

if (
false === file($configPath)) {
    echo
'Config path is not existed.' . PHP_EOL;
    exit(
1);
}

require_once
$composerLoadPath;
require_once
$configPath;

use
Carbon\Carbon;
use
GuzzleHttp\Client;
use
Vonage\SMS\Message\SMS;
use
Vonage\Client as VonageClient;
use
Vonage\Client\Credentials\Basic;
use
Vonage\SMS\Exception\Request;
use
Mailjet\Resources;
use
Mailjet\Client as MailjetClient;
use
Symfony\Component\DomCrawler\Crawler;

function
sendEmail($message): void {
   
$mj = new MailjetClient(MJ_APIKEY_PUBLIC, MJ_APIKEY_PRIVATE, true, ['version' => 'v3.1']);
   
$body = [
       
'Messages' => [
            [
               
'From' => [
                   
'Email' => SENDER_EMAIL,
                   
'Name' => "Emask Notifier"
               
],
               
'To' => [
                    [
                       
'Email' => RECIPIENT_EMAIL,
                       
'Name' => "You"
                   
]
                ],
               
'Subject' => "Emask Notifier Status",
               
'TextPart' => $message,
               
'HTMLPart' => "<h3>$message</h3>",
           ]
        ]
    ];

   
$response = $mj->post(Resources::$Email, ['body' => $body]);
}

function
sendSMS($notificationMessage): bool {
   
$welcomeMessageFormat = "Hi %s,\n";
   
$phoneFilePath = __DIR__ . '/phone.csv';

    if (
false === file_exists($phoneFilePath)) {
        echo
'Cannot find phone.csv file!' . PHP_EOL;
        exit(
1);
    }
   
$handler = fopen($phoneFilePath, 'r');
    while (
false === feof($handler)) {
       
$str = (string)fgets($handler, 4096);
        if (
'' === $str) {
            break;
        }
       
$row = str_getcsv($str);
       
$userName = $row[0];
       
$userPhoneNumber = $row[1];
       
$message = sprintf($welcomeMessageFormat, $userName) . $notificationMessage;

        if (
false === defined('VONAGE_API_KEY')) {
            echo
'VONAGE_API_KEY is not defined!' . PHP_EOL;
            exit(
1);
        }

        if (
false === defined('VONAGE_API_SECRET')) {
            echo
'VONAGE_API_KEY is not defined!' . PHP_EOL;
            exit(
1);
        }

       
$basic = new Basic(VONAGE_API_KEY, VONAGE_API_SECRET);
       
$client = new VonageClient($basic);
       
$response = $client->sms()->send(
            new
SMS($userPhoneNumber, $userName, $message)
        );
       
$current = $response->current();

        echo
sprintf('[%s] Message has been sent to %s. Message ID: %s', (string)Carbon::now($timezone), $userName, $current->getMessageId()) . PHP_EOL;
    }

   
fclose($handler);

    return
true;
}

if (
'10:00' !== Carbon::now($timezone)->format('H:i')) {
    echo
'Sorry! This worker only works at 10:00 every day' . PHP_EOL;
    exit(
0);
}

$client = new Client();
$response = $client->request('GET', 'https://emask.taiwan.gov.tw/msk/index.jsp');
$body = (string)$response->getBody();

$crawler = new Crawler($body);
$notificationMsgLists = [];
$notificationElements = 'p[style="margin-top: 10px; margin-bottom: 10px; font-size: 14px; font-weight: 400;"]';
$crawler->filter($notificationElements)->reduce(function(Crawler $node, $index) use (&$notificationMsgLists) {
   
$notificationMsgLists[$index] = $node->text();
});

if (
5 !== count($notificationMsgLists)) {
    echo
'Notification Message fetching Error!' . PHP_EOL;
    exit(
1);
}
array_pop($notificationMsgLists);

$notificationMessage = implode("\n", $notificationMsgLists);

$dateCount = preg_match_all('/(\d+\/\d+ \d+:\d+ - \d+\/\d+ \d+:\d+)/', $notificationMsgLists[2], $matched);
if (
1 !== $dateCount) {
    echo
'Cannot filter date range!' . PHP_EOL;
    exit(
1);
}

$now = Carbon::now($timezone);
$dateRange = explode(' - ', $matched[0][0]);
$startDate = $dateRange[0];
$endDate = $dateRange[1];

if (
0 === $now->diff(Carbon::parse($startDate))->days) {
    echo
'Sending Message!' . PHP_EOL;

    try {
       
$result = sendSMS($notificationMessage);
    } catch (
Request $e) {
       
$message = sprintf('[%s]Send SMS Message is failed: %s', (string)$now, $e->getMessage());
        echo
$message . PHP_EOL;
       
sendEmail($message);
        exit(
1);
    }

    if (
false === $result) {
        echo
sprintf('[%s]Sending Notification Message has been failed!', (string)$now) . PHP_EOL;
        exit(
1);
    }

    echo
sprintf('[%s]Sending Notification Message has been done!', (string)$now) . PHP_EOL;
    exit(
0);
}

$now->addDay(-1);
if (
0 === $now->diff(Carbon::parse($startDate))->days) {
    echo
'Sending Message!' . PHP_EOL;
   
$result = sendSMS($notificationMessage);

    if (
false === $result) {
        echo
sprintf('[%s]Sending Notification Message has been failed!', (string)$now) . PHP_EOL;
        exit(
1);
    }

    echo
sprintf('[%s]Sending Notification Message has been done!', (string)$now) . PHP_EOL;
    exit(
0);
}

echo
sprintf('[%s] Do Nothing!', (string)$now) . PHP_EOL;


Details

emask-notifier

Introduction

Using the Nexmo API to make SMS message with specific phone number and user.

Emask Notifier Installation (Deprecated)

  • Set up a Nexmo account on Nexmo developer site
  • Creating `phone.csv` and locate this CSV file is with `emask-notifier.sh` on same directory.

And the format is as follows:

user_name,user_phone
  • Set `api_key` as a system environment variable with `echo 'export api_key="{your_api_key}"' | sudo tee -a /etc/environment` on `/etc/environment` file
  • Set `api_secret` as a system environment variable with `echo 'export api_secret="{your_api_secret}"' | sudo tee -a /etc/environment` on `/etc/environment` file
  • Using `cd /path/to/emask-notifier/ && ./emask-notifier.sh` as a Cronjob to let this Bash script do work automatically.
  • Done. Happy to do notification for your friends :)!

Emask Notifier Uninstallation (Deprecated)

  • Remove `api_key` system environment variable on `/etc/environment` file
  • Remove `api_secret` system environment variable on `/etc/environment` file
  • Remove this Cronjob work.

Emask Notifier for notifier.php Installation

  • Checking the `supervisor`, `curl` and `cron` commands have been available on deployed operating system.
  • `PHP 7.4` has been installed on Ubuntu operating system.
  • Download `composer.phar` with `curl -sS https://getcomposer.org/installer | php7.4` command.
  • Running `php composer.phar update -n` command.
  • Creating the `.env` to setup the `VONAGE_API_KEY`, `VONAGE_API_SECRET`, `SENDER_EMAIL`, `RECIPIENT_EMAIL`, `MJ_APIKEY_PUBLIC` and `MJ_APIKEY_PRIVATE` variables.
  • Creating the `phone.csv` to setup the user phone number lists.
  • Running the `notifier_php_builder.sh` script to setup all of above works.

Emask Notifier for notifier.php Uninstallation

  • We assume that this uninstallation work is running with non-root user.
  • Stopping notifier worker with `sudo rm /etc/supervisor/conf.d/notifier-php.conf`
  • Restarting supervisor service with `sudo systemctl restart supervisor`
  • Removing this repository with `rm -rf /path/to/emask-notifier`

  Files folder image Files  
File Role Description
Accessible without login Plain text file .env.example Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file config.php Example Example script
Accessible without login Plain text file emask_notifier.sh Data Auxiliary data
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file notifier.php Example Example script
Accessible without login Plain text file notifier_php_builder.sh Data Auxiliary data
Accessible without login Plain text file phone.csv.example Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

 Version Control Unique User Downloads  
 100%
Total:0
This week:0